[英]Play sound and count time simultaneously
I have the following function that is part of a stopwatch program I am writing, and It will count down from a given time but for that last 5, it will play an audio clip.我有以下 function 是我正在编写的秒表程序的一部分,它会从给定的时间倒计时,但对于最后 5 个,它将播放音频剪辑。 Basically, the function should count down from 5 at 1 second intervals.基本上,function 应该以 1 秒的间隔从 5 倒计时。 However, the length of the time of the audio clip is added to the time interval of the program executing.但是,音频剪辑的时间长度会添加到程序执行的时间间隔中。 So it's 1 second + the length of the audio clip.所以它是 1 秒 + 音频剪辑的长度。 I've tried moving the time.sleep to before the if conditional, but it's still the same net gain.我已经尝试将 time.sleep 移到 if 条件之前,但它仍然是相同的净收益。 Is there any way to have the while loop run exactly every second, regardless if there is a sound bit being played?有没有办法让 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
As the code is executing in a sequential manner ie, play a sound and then wait for 1 second, the total would be 1 second + length of sound.由于代码是按顺序执行的,即播放声音然后等待 1 秒,因此总时间为 1 秒 + 声音长度。 If you want to ensure total is 1 second, you have two options如果要确保总计为 1 秒,则有两种选择
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.