Frage

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()
War es hilfreich?

Lösung

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

Andere Tipps

Set a variable for your loop and then check mixer.music.get_busy() to determine whether your loop should stop.

from pygame import mixer

filename =  "mymusic.mp3"

x = mixer.init(frequency=44100)
mixer.music.load(filename)
mixer.music.play()

run = True
while run: 
    # ..do some stuff
    pos = mixer.music.get_pos() / 1000
    print('pos', pos)
    
    if mixer.music.get_busy() == False:
        run = False
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top