Playing music with Pygame unreliable

2019-08-03 20:31发布

问题:

I'm trying to write a simple program to play music files with Pygame. My script is below.

import pygame

import sys
import time

FRAMERATE = 30

if len(sys.argv) < 2:
   sys.exit(2)

filename = sys.argv[1]

clock = pygame.time.Clock()

pygame.init()

pygame.mixer.init(frequency=44100)
pygame.mixer.music.load(filename)
print "%s loaded!" % filename
pygame.mixer.music.play(1)

while pygame.mixer.music.get_busy():
   clock.tick(FRAMERATE)

But I'm having some puzzling problems. The "[File name] loaded!" message always prints, but sometimes it never enters the loop and exits immediately. If I check on the status of pygame.mixer.music.get_busy(), it appears to be false immediately after the pygame.mixer.music.play(1) command. This happens erratically; I just tried running the program with no changes to the code, having it work once and encounter this problem once right afterward. Does anyone know what could be causing these seemingly random playback problems?

回答1:

I imagine this is because the actual music playback is happening on another thread, so it sometimes hasn't finished starting at the point you first call get_busy().

If that's the case, it seems like a bug in either pygame or SDL_mixer (which pygame uses.)

As an alternative way of checking for music completion, you can get pygame to give you an event when the music finishes and check for that. Like this:

pygame.mixer.music.set_endevent(pygame.USEREVENT)

quit = False
while not quit:
   clock.tick(FRAMERATE)
   for event in pygame.event.get():
      if event.type == pygame.QUIT: 
        quit = True
      if event.type == pygame.USEREVENT: 
        print "Music ended"
        quit = True


标签: python pygame