0

我有以下功能,它是我正在编写的秒表程序的一部分,它会从给定的时间开始倒计时,但对于最后 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
4

1 回答 1

1

由于代码是按顺序执行的,即播放声音然后等待 1 秒,因此总时间为 1 秒 + 声音长度。如果要确保总计为 1 秒,则有两种选择

  1. 在单独的线程中播放声音(请检查 python 中的多线程)
  2. 将声音的长度从 1 秒减少,然后在剩余时间上应用睡眠
于 2021-03-09T05:07:00.233 回答