I'm trying to use this tutorial to run pygame instead of Mplayer in my script:
So, in the code:
import pygame
pygame.init()
song = pygame.mixer.Sound(my_song.ogg)
clock = pygame.time.Clock()
song.play()
while True:
clock.tick(60)
pygame.quit()
print "done" # not appears
exit()
The song is playing well, but "done" is never printed in the console. The program stays in the loop... How to fix it ? Thanks
Edit: I found this, it's working well, with a 10 second song:
import pygame
import time
pygame.init()
song = pygame.mixer.Sound(son)
clock = pygame.time.Clock()
song.play()
while True:
clock.tick(60)
time.sleep(10)
break
pygame.quit()
print "done"
exit()
You have several problems with the two examples provided.
First:
while True:
clock.tick(60)
is an infinite loop in any context, not just pygame
, and will never exit.
Next:
while True:
clock.tick(60)
time.sleep(10)
break
will just break
on its first time through the loop and is equivilent to
clock.tick(60)
time.sleep(10)
which is why it works fine for a 10
second song.
If you want to use pygame.mixer.Sound
you should do it like this, using Sound.get_length()
import pygame
import time
pygame.init()
song = pygame.mixer.Sound("my_song.ogg")
clock = pygame.time.Clock()
song.play()
time.sleep(song.get_length()+1) # wait the length of the sound with one additional second for a safe buffer
pygame.quit()
print "done"
exit()
pygame
recommends using mixer.music
for things like this:
import pygame
import time
pygame.init()
pygame.mixer.music.load("my_song.ogg")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
pygame.quit()
print "done"
exit()
See this answer for reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With