同时播放声音和计时

时间:2021-03-09 03:54:29

标签: python time playsound

我有以下功能,它是我正在编写的秒表程序的一部分,它会从给定时间开始倒计时,但对于最后 5 个,它将播放音频剪辑。基本上,该函数应该以 1 秒的间隔从 5 开始倒计时。但是,音频剪辑的时间长度被添加到程序执行的时间间隔中。所以它是 1 秒 + 音频剪辑的长度。我试过将 time.sleep 移到 if 条件之前,但它仍然是相同的净收益。有没有办法让 while 循环精确地每秒运行一次,无论是否播放声音?

def countdown(timer_count,count_type):
    counter = timer_count
    count_type = count_type
    while counter >= 0:
        COUNT_DOWN_TEXT.config(text=f"{count_type} for: {counter}")
        main.update()
        if counter == 1:
            playsound('sound/1-sec-daisy.mp3')
        elif counter == 2:
            playsound('sound/2-sec-daisy.mp3')
        elif counter == 3:
            playsound('sound/3-sec-daisy.mp3')
        elif counter == 4:
            playsound('sound/4-sec-daisy.mp3')
        elif counter == 5:
            playsound('sound/5-sec-daisy.mp3')
        time.sleep(1)
        counter -= 1
        print(counter)
    if count_type != "workout":
        count_type = "workout"
    elif count_type == "workout":
        count_type = "rest"
    return count_type

1 个答案:

答案 0 :(得分:1)

由于代码以顺序方式执行,即播放声音然后等待 1 秒,总时间为 1 秒 + 声音长度。 如果你想确保总时间为 1 秒,你有两个选择

  1. 在单独的线程中播放声音(请检查 python 中的多线程)
  2. 将声音的长度从 1 秒缩短,然后在剩余的时间内应用睡眠
相关问题