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程序设计有所帮助。
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短