实现的方法可能有很多种,这里我主要使用的是wave+pyAudio来实现。
阻塞调用方式
import os
import pyaudio
import wave
CHUNK = 1024
# 1. Get the file path to the included audio example
audio_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "audio")
audio_file = os.path.join(audio_path, "node2.wav")
print("audio_file :",audio_file )
wf = wave.open(audio_file, 'rb')
print("samplewidth:", wf.getsampwidth())
print("channles:",wf.getnchannels())
print("framerate:",wf.getframerate())
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate= wf.getframerate(),
output=True)
data = wf.readframes(CHUNK)
while len(data) >0:
stream.write(data)
data = wf.readframes(CHUNK)
stream.stop_stream()
stream.close()
wf.close()
p.terminate()
回调调用方式
import os
import pyaudio
import wave
import time
def callback(in_data, frame_count, time_info, status):
data = wf.readframes(frame_count)
return (data, pyaudio.paContinue)
# 1. Get the file path to the included audio example
audio_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "audio")
audio_file = os.path.join(audio_path, "node2.wav")
print("audio_file :",audio_file )
wf = wave.open(audio_file, 'rb')
print("samplewidth:", wf.getsampwidth())
print("channles:",wf.getnchannels())
print("framerate:",wf.getframerate())
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate= wf.getframerate(),
output=True,
stream_callback=callback)
stream.start_stream()
while stream.is_active():
time.sleep(0.1)
stream.stop_stream()
stream.close()
wf.close()
p.terminate()
网友评论