Gui*_*ume 1 python pygame quit
我正在尝试使用本教程在我的脚本中运行pygame而不是Mplayer:
所以,在代码中:
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()
Run Code Online (Sandbox Code Playgroud)
这首歌很好玩,但"完成"从未打印在控制台中.该程序保持循环...如何解决?谢谢
编辑:我发现了这个,它运行良好,有10秒钟的歌曲:
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()
Run Code Online (Sandbox Code Playgroud)
提供的两个示例有几个问题.
第一:
while True:
clock.tick(60)
Run Code Online (Sandbox Code Playgroud)
在任何上下文中都是一个无限循环,不仅仅是pygame,并且永远不会退出.
下一个:
while True:
clock.tick(60)
time.sleep(10)
break
Run Code Online (Sandbox Code Playgroud)
将break在第一次通过循环并且是等效的
clock.tick(60)
time.sleep(10)
Run Code Online (Sandbox Code Playgroud)
这就是为什么它适用于10第二首歌的原因.
如果你想使用pygame.mixer.Sound你应该这样做,使用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()
Run Code Online (Sandbox Code Playgroud)
pygame建议使用这样mixer.music的东西:
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()
Run Code Online (Sandbox Code Playgroud)