Pygame sound keeps repeating

狂风中的少年 提交于 2021-02-10 06:44:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!