基于pyaudio利用Python編程實(shí)現(xiàn)播放音頻mp3、wav等格式文件
輸出結(jié)果
實(shí)現(xiàn)代碼
T1、while循環(huán)輸出數(shù)據(jù)流的方法
def play():
chunk=1024 #2014kb
wf=wave.open(r"16k.wav",'rb')
p=PyAudio()
stream=p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=wf.getnchannels(),rate=wf.getframerate(),output=True)
data = wf.readframes(chunk) # 讀取數(shù)據(jù)
print(data)
while data != '': # 播放
stream.write(data)
data = wf.readframes(chunk)
print('while循環(huán)中!')
print(data)
stream.stop_stream() # 停止數(shù)據(jù)流
stream.close()
p.terminate() # 關(guān)閉 PyAudio
print('play函數(shù)結(jié)束!')
T2、while循環(huán)輸出+if判斷數(shù)據(jù)流的方法
def play():
chunk=1024 #2014kb
wf=wave.open(r"16k.wav",'rb')
p=PyAudio()
stream=p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=wf.getnchannels(),rate=wf.getframerate(),output=True)
data = wf.readframes(chunk) # 讀取數(shù)據(jù)
while True:
data=wf.readframes(chunk)
if data=="":
break
stream.write(data)
stream.stop_stream() # 停止數(shù)據(jù)流
stream.close()
p.terminate() # 關(guān)閉 PyAudio
print('play函數(shù)結(jié)束!')
if __name__ == '__main__':
audio_file='16k.wav' #指定錄音文件
play() #播放錄音文件