接觸過Pygame,你應該知道如何去播放音效檔案,也就是播放WAV格式的檔案。如果你隻是粗略的了解Pygame,你可能會以為它任何WAV格式的檔案都能夠播放,但事實并非如此。有時候,并不是代碼的錯,隻是我們了解的還不夠。下面是段測試代碼:
- import pygame
- import os
- def init_game(strcaption,width=800,height=600):
- pygame.init()
- pygame.mixer.init()
- screen=pygame.display.set_mode((width,height))
- pygame.display.set_caption(strcaption)
- return screen
- def play_sound(file):
- realpath=os.path.abspath(file)
- sound=pygame.mixer.Sound(realpath)
- sound.play()
- print "Start Test"
- SCREEN=init_game('SoundTest')
- while True:
- for event in pygame.event.get():
- if event.type==pygame.QUIT:
- exit()
- SCREEN.fill((255,255,255))
- mousebtn=pygame.mouse.get_pressed()
- if mousebtn[0]==1:
- print 'Play'
- play_sound('test.wav') # 替換你要播放的檔案名
附件中包含兩份WAV檔案,test.wav是可以正常播放的音效檔案,test1.wav是我在網易的itown sdk官方站點上下載下傳的一個音效素材,但是它并不能夠被正常播放。為什麼呢?Pygame官方文檔的解釋是它支援非壓縮的WAV格式檔案,對于壓縮的WAV格式檔案并不能夠支援。我想網易的素材應該是壓縮的WAV格式檔案。玩Pygame的童鞋們,一定要多多注意哦!