问题
I am trying to play a sound at the end of a game when there is a lose. Previously this code below worked with Python 3.5 but it would abort after it played the sound. I upgraded to python 3.6 and now it just keeps on repeating. How can I play the sound until the end?
import pygame
def sound():
pygame.mixer.init()
sound1 = pygame.mixer.Sound('womp.wav')
while True:
sound1.play(0)
return
回答1:
while True
is an endless loop:
while True: sound1.play(0)
The sound will be played continuously.
Use get_length() to get the length of the sound in seconds. And wait till the sound has end:
(The argument to pygame.time.wait() is in milliseconds)
import pygame
pygame.mixer.init()
my_sound = pygame.mixer.Sound('womp.wav')
my_sound.play(0)
pygame.time.wait(int(my_sound.get_length() * 1000))
Alternatively you can test if any sound is being mixed by pygame.mixer.get_busy(). Run a loop as long a sound is mixed:
import pygame
pygame.init()
pygame.mixer.init()
my_sound = pygame.mixer.Sound('womp.wav')
my_sound.play(0)
clock = pygame.time.Clock()
while pygame.mixer.get_busy():
clock.tick(10)
pygame.event.poll()
来源:https://stackoverflow.com/questions/60013591/pygame-sound-keeps-repeating