简体   繁体   English

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

[英]Python pygame.mixer does not play music infinitely

I want to play an alarm wave file continuously until it detects a button is pushed. 我想连续播放一个闹钟文件,直到它检测到一个按钮被按下为止。 In this case I use a keyboard interrupt to try. 在这种情况下,我使用键盘中断来尝试。

Here is my script: 这是我的脚本:

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

However it only played once and it stops and exits the script. 但是,它只播放一次,然后停止并退出脚本。 What's wrong? 怎么了?

UPDATE: I manage to let it run and terminate upon keyboard interrupt but I don't understand why play(-1) doesn't work? 更新:我设法让它运行并在键盘中断时终止,但我不明白为什么play(-1)无法正常工作?

This is my working script: 这是我的工作脚本:

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 manual says about pygame手册说关于

pygame.mixer.music.get_busy()

Returns True when the music stream is actively playing. 当音乐流正在播放时,返回True。 When the music is idle this returns False. 当音乐空闲时,它返回False。

So the problem is, that this functions returns False in the little gap when the sound ends and is going to start again. 因此,问题在于,当声音结束并要重新开始时,此函数会在很小的间隙中返回False。 This is the reason your 2nd version works. 这就是您的第二个版本起作用的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM