简体   繁体   中英

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?

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.mixer.music.get_busy()

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

So the problem is, that this functions returns False in the little gap when the sound ends and is going to start again. This is the reason your 2nd version works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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