python使用PyGame播放Midi和Mp3文件的方法
本文实例讲述了python使用PyGame播放Midi和Mp3文件的方法。分享给大家供大家参考。具体实现方法如下:
'''pg_midi_sound101.py playmidimusicfiles(alsomp3files)usingpygame testedwithPython273/331andpygame192byvegaseat ''' importpygameaspg defplay_music(music_file): ''' streammusicwithmixer.musicmoduleinblockingmanner thiswillstreamthesoundfromdiskwhileplaying ''' clock=pg.time.Clock() try: pg.mixer.music.load(music_file) print("Musicfile{}loaded!".format(music_file)) exceptpygame.error: print("File{}notfound!{}".format(music_file,pg.get_error())) return pg.mixer.music.play() #checkifplaybackhasfinished whilepg.mixer.music.get_busy(): clock.tick(30) #pickamidiorMP3musicfileyouhaveintheworkingfolder #orgivefullpathname music_file="Latin.mid" #music_file="Drumtrack.mp3" freq=44100#audioCDquality bitsize=-16#unsigned16bit channels=2#1ismono,2isstereo buffer=2048#numberofsamples(experimenttogetrightsound) pg.mixer.init(freq,bitsize,channels,buffer) #optionalvolume0to1.0 pg.mixer.music.set_volume(0.8) try: play_music(music_file) exceptKeyboardInterrupt: #ifuserhitsCtrl/Cthenexit #(worksonlyinconsolemode) pg.mixer.music.fadeout(1000) pg.mixer.music.stop() raiseSystemExit
希望本文所述对大家的Python程序设计有所帮助。