Pygame sound keeps repeating

Colorful Codes

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

Rabbid76

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related