Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In pygame (or even in python in general), how would I create a loop that keeps executing while a sound is playing?

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!

like image 715
Alkamyst Avatar asked Dec 05 '22 15:12

Alkamyst


2 Answers

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'.

like image 200
J. P. Petersen Avatar answered Dec 07 '22 04:12

J. P. Petersen


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.

like image 27
user1557602 Avatar answered Dec 07 '22 05:12

user1557602