Jerry Pass
Jerry Pass

Reputation: 105

How can I play audio at the end of my python pygame project?

I have created a connect four game and I have implemented a sound effect of dropping a chip using pygame.mixer.Sound.play to play a short .mp3 file.

However, once the game is over, I cannot get the .mp3 file to play that I would like to use then. The pygame screen closes and the program exits successfully.

My main.py has a "while not game_over" loop. And I attempted to play the song after that loop exited and a player had won, but that was unsuccessful, I also attempted to use sleep to stop the program from exiting but that also failed. I would like to put the command to play the music in my winCheck function like below, but as I previously stated the program just exits and the song does not play.

Any help would be appreciated, my attempt to add it to a winCheck function is shown below:

if count >= 4:
    win = pygame.mixer.Sound("sounds/win.mp3")
    pygame.mixer.Sound.play(win)
    return True

Upvotes: 1

Views: 844

Answers (2)

Dustin
Dustin

Reputation: 108

Try to add time.sleep or to use pygame.mixer.get_busy() to wait till your Sound/Music has finished playing. My choice would be something like this:while pygame.mixer.get_busy() == 1: time.sleep(1)

Upvotes: 1

Rabbid76
Rabbid76

Reputation: 211277

You have to wait for the music to finish playing:

win = pygame.mixer.Sound("sounds/win.mp3")
win.play()
while pygame.mixer.get_busy():
    pygame.time.delay(10)
    pygame.event.poll()

Upvotes: 3

Related Questions