天天看點

你不知道的事之Pygame播放音效

    接觸過Pygame,你應該知道如何去播放音效檔案,也就是播放WAV格式的檔案。如果你隻是粗略的了解Pygame,你可能會以為它任何WAV格式的檔案都能夠播放,但事實并非如此。有時候,并不是代碼的錯,隻是我們了解的還不夠。下面是段測試代碼:

  1. import pygame 
  2. import os 
  3. def init_game(strcaption,width=800,height=600): 
  4.     pygame.init() 
  5.     pygame.mixer.init() 
  6.     screen=pygame.display.set_mode((width,height)) 
  7.     pygame.display.set_caption(strcaption) 
  8.     return screen 
  9. def play_sound(file): 
  10.     realpath=os.path.abspath(file) 
  11.     sound=pygame.mixer.Sound(realpath) 
  12.     sound.play() 
  13. print "Start Test" 
  14. SCREEN=init_game('SoundTest') 
  15. while True: 
  16.     for event in pygame.event.get(): 
  17.         if event.type==pygame.QUIT: 
  18.             exit() 
  19.     SCREEN.fill((255,255,255)) 
  20.     mousebtn=pygame.mouse.get_pressed() 
  21.     if mousebtn[0]==1: 
  22.         print 'Play' 
  23.         play_sound('test.wav') # 替換你要播放的檔案名

附件中包含兩份WAV檔案,test.wav是可以正常播放的音效檔案,test1.wav是我在網易的itown sdk官方站點上下載下傳的一個音效素材,但是它并不能夠被正常播放。為什麼呢?Pygame官方文檔的解釋是它支援非壓縮的WAV格式檔案,對于壓縮的WAV格式檔案并不能夠支援。我想網易的素材應該是壓縮的WAV格式檔案。玩Pygame的童鞋們,一定要多多注意哦!

繼續閱讀