python - Python pygame.mixer不会无限播放音乐

标签 python audio pygame

我想连续播放一个闹钟文件,直到它检测到一个按钮被按下为止。在这种情况下,我使用键盘中断来尝试。

这是我的脚本:

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()

最佳答案

pygame手册说关于

pygame.mixer.music.get_busy()

Returns True when the music stream is actively playing. When the music is idle this returns False.



因此,问题在于,当声音结束并要重新开始时,此函数会在很小的间隙中返回False。这就是您的第二个版本起作用的原因。

关于python - Python pygame.mixer不会无限播放音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22979174/

相关文章:

java - 在java中播放wav文件

java - Java 中的音频 : Why am I getting `null` ?

ios - 如果播放之间> 1秒,AVAudioPlayer和AudioServices都会延迟声音

python - Pygame 朝某个方向移动图像

python - 使用 pygame 单击并拖动一个矩形

python - 使用 for 循环更改列表中的值 (python)

python - 最小化带有 2 个参数的函数

python - AttributeError: 'Event' 对象没有属性 'key'

python - Python 中的分层数据遍历和表示

javascript - 如何在Python应用程序中显示网站