2012-04-08 98 views
0

我使用下面的代碼在Python中使用pygame庫播放歌曲。它播放歌曲,我可以聽到聲音,如果我直接點擊我的Python文件。但是,如果我使用python(命令行)或python(GUI)運行我的程序,我聽不到聲音。我檢查了python 2.6和2.7。我正在使用Windows 7操作系統。聽不到pygame的聲音

我的代碼:

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

你需要做一個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) 
+0

它刪除「pygame.init()」行後工作。 – chom 2012-04-10 03:06:52