听不到pygame的声音

时间:2012-04-08 23:08:35

标签: python pygame

我使用以下代码在python中使用pygame库播放一首歌。它播放歌曲,如果我直接点击我的python文件,我可以听到声音。但是,如果我使用python(命令行)或python(GUI)运行我的程序,我听不到声音。我检查了python 2.6和2.7。我正在使用Windows 7操作系统。

我的代码:

import pygame,time,sys

pygame.init()

pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)

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("2.mp3")

while 1:

    selection = raw_input()

    if selection == "play":

        print "Playing"

        pygame.mixer.music.play()

    elif selection == "rewind":

        pygame.mixer.music.rewind()

    elif selection == "pause":

        pygame.mixer.music.pause()

    elif selection == "stop":

        pygame.mixer.music.stop()

    elif selection == "queue":

        inputqueue = raw_input()

        pygame.mixer.music.queue(inputqueue)

    else:

        print "invalid selection"

        sys.stdout.flush()

1 个答案:

答案 0 :(得分:1)

你需要制作一个pygame循环,这样你才能听音乐。您应该使用密钥库http://www.pygame.org/docs/ref/key.html来获取输入

import pygame,time,sys

#pygame.init()
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
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("2.mp3")
pygame.mixer.music.play()

clock = pygame.time.Clock()
while pygame.mixer.music.get_busy():
   # check if playback has finished
   clock.tick(30)