0

我正在使用以下代码在 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()
4

1 回答 1

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)
于 2012-04-09T02:12:18.517 回答