我试图用pygame播放一首歌,但它没有播放这首歌。
我的代码:
import pygame,time
pygame.init()
print "Mixer settings", pygame.mixer.get_init()
print "Mixer channels", pygame.mixer.get_num_channels()
pygame.mixer.music.set_volume(1.0)
pygame.mixer.music.load('C:/1.mp3')
print "Play"
pygame.mixer.music.play(0)
while pygame.mixer.music.get_busy():
print "Playing", pygame.mixer.music.get_pos()
time.sleep(1)
print "Done"
我得到的输出为
Mixer settings (22050, -16, 2)
Mixer channels 8
Play
Done
您的代码适用于我,在运行Python 2.7.2的Lubuntu 11.10上,使用我从Youtube剪辑转换的MP3。你检查过mp3不是零长度的吗?你试过wav文件吗?
由于没有其他解释,我认为如果play(0)
调用还没有完成进程或线程的启动,那么pygame.mixer.music.get_busy()
可能会返回false。这将导致您的代码跳过while循环,打印"完成"并终止,删除音乐播放器对象并在听到任何内容之前终止播放。如果这是问题所在,您可以在play(0)
之后和print Done
:之前尝试类似的操作
pygame.mixer.music.set_endevent(pygame.USEREVENT)
finishedPlaying = False
while not finishedPlaying:
for event in pygame.event.get():
if event.type == pygame.USEREVENT:
finishedPlaying = True
break # only because we don't care about any other events
print "Playing", pygame.mixer.music.get_pos() # will print -1 on the last iteration
在pygame.mixer.music.play的评论中,我发现了这个:
November 18, 2010 7:30pm - Anonymous
Work Exmpl:
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
sound = pygame.mixer.Sound('Time_to_coffee.wav').play()
此外,您发送0作为您想要重复的次数感谢Iskar Jarak,-1是无穷大的。
http://www.pygame.org/docs/ref/music.html#pygame.mixer.music.play