5

In pygame is there a way to tell if a sound has finished playing? I read the set_endevent and get_endevent documentation but I can't make sense of it or find an example.

I'm trying to specifically do the following:

  1. play a sound
  2. While the sound is playing keep iterating on a loop
  3. When the sound has finished playing, move on.

I did check the other questions that were asked - didnt find anything specifically targeting python / pygame.

Thanks!

hammythepig
  • 947
  • 2
  • 8
  • 30
Alkamyst
  • 51
  • 1
  • 2

4 Answers4

11

The trick is that you get an object of type pygame.mixer.Channel when you call the play() method of a sound (pygame.mixer.Sound). You can test if the sound is finished playing using the channel's get_busy() method.

A simple example:

import pygame.mixer, pygame.time

mixer = pygame.mixer

mixer.init()
tada = mixer.Sound('tada.wav')
channel = tada.play()

while channel.get_busy():
    pygame.time.wait(100)  # ms
    print "Playing..."
print "Finished."

The examples assumes you have a sound file called 'tada.wav'.

J. P. Petersen
  • 4,871
  • 4
  • 33
  • 33
7

You can use some code like this:

import pygame
pygame.mixer.music.load('your_sound_file.mid')
pygame.mixer.music.play(-1, 0.0)
while pygame.mixer.music.get_busy() == True:
    continue

And, it doesn't have to be a .mid file. It can be any file type pygame understands.

user1557602
  • 127
  • 4
2

To use set_endevent you have to do something like this:

# You can have several User Events, so make a separate Id for each one
END_MUSIC_EVENT = pygame.USEREVENT + 0    # ID for music Event

pygame.mixer.music.set_endevent(END_MUSIC_EVENT)

running = True

# Main loop
while running:
    events = pygame.event.get()
    if events:
        for event in events:
            ...
            if event.type == END_MUSIC_EVENT and event.code == 0:
                print "Music ended"
            ...
pmoleri
  • 4,238
  • 1
  • 15
  • 25
0
pygame.mixer.pre_init(44100, 16, 2, 4096) # setup mixer to avoid sound lag
pygame.init()
startmusic="resources\snd\SGOpeningtheme.ogg"
pygame.mixer.set_num_channels(64) # set a large number of channels so all the game sounds will play WITHOUT stopping another
pygame.mixer.music.load(startmusic)
pygame.mixer.music.set_volume(0.3)
pygame.mixer.music.play(-1) # the music will loop endlessly

once the above code is executed the music will continue to play until you stop it or fade out as per the pygame site info. You can loop to your heart content and the music will continue. If you need the music to play twice, instead of -1 put 1. Then the music will PLAY once and REPEAT ONCE. You can check if the stream is playing by doing pygame.mixer.music.get_busy(). If it returns True it is. False means it has finished.

wookie
  • 329
  • 1
  • 5
  • 13