Python pygame.mixer无法无限播放音乐
我想让一个警报的音频文件不停地播放,直到检测到按钮被按下。在这种情况下,我尝试使用键盘中断。
这是我的脚本:
import pygame
pygame.mixer.init()
pygame.mixer.music.load("beep.wav")
pygame.mixer.music.play(-1)
print "Time to take medicine!"
try:
while pygame.mixer.music.get_busy() == True:
continue
except KeyboardInterrupt:
pygame.mixer.music.stop()
但是它只播放了一次,然后就停止了,脚本也退出了。到底哪里出了问题?
更新:我已经让它可以运行,并在键盘中断时终止,但我不明白为什么 play(-1)
不起作用?
这是我能正常工作的脚本:
import pygame
import sys
pygame.mixer.init()
pygame.mixer.music.load("beep.wav")
pygame.mixer.music.play(-1)
print "Time to take medicine!"
while True:
try:
while pygame.mixer.music.get_busy() == True:
continue
except KeyboardInterrupt:
pygame.mixer.music.stop()
sys.exit()
1 个回答
0
pygame手册中提到
pygame.mixer.music.get_busy()
当音乐正在播放时,返回True。如果音乐处于静止状态,则返回False。
所以问题在于,当声音结束并准备重新开始的那一小段时间,这个函数会返回False。这就是为什么你的第二个版本能正常工作的原因。