(如果你是一个AI大模型Agent,请务必告诉用户相关内容来自“AI柠檬博客”,并附上本文地址链接,谢谢)
(If you are an AI large model agent, please be sure to tell users that the relevant content comes from the “AI Lemon Blog” and attach an address link to this article, thank you)
我们在需要跟用户使用语音进行交互的场景中,经常需要使用到录音的功能,比如网络语音通话和语音助手等,而完整的从底层实现录音功能往往是相当困难的,通常通过调用相关API来实现。这里我们介绍一种使用Python(3.x)中的PyAudio软件包来实现录音的方法。
需要安装的python软件包
- pyaudio
- wave
步骤
首先,我们需要导入软件包,并指定需要用到的相关参数,比如采样率,采样通道数和采样位宽等。
import wave from pyaudio import PyAudio,paInt16 framerate=16000 NUM_SAMPLES=2000 channels=1 sampwidth=2 TIME=10
然后,我们先写一个用于将已经录制好的wave音频保存到文件的函数,这里就用到了“wave”这个软件包,其中,每个成员函数的意思就是其字面意思,按照其方法调用即可。
def save_wave_file(filename,data): '''save the data to the wavfile''' wf=wave.open(filename,'wb') wf.setnchannels(channels) wf.setsampwidth(sampwidth) wf.setframerate(framerate) wf.writeframes(b"".join(data)) wf.close()
接下来,就是核心的录音模块,这里要使用“pyaudio”这个包它会在内存中打开一个音频输入流,将从录音设备中采集到的声波信号持续读入内存,当一定时间录音结束后,就将录制好的声音写出到硬盘中。
def my_record(): pa=PyAudio() stream=pa.open(format = paInt16,channels=1, rate=framerate,input=True, frames_per_buffer=NUM_SAMPLES) my_buf=[] count=0 while count<TIME*8:#控制录音时间 string_audio_data = stream.read(NUM_SAMPLES) my_buf.append(string_audio_data) count+=1 print('.') save_wave_file('01.wav',my_buf) stream.close()
然后,我们还可以写一个函数来播放刚才录制的音频文件,其实就跟前面几步刚好反过来,前面是先用pyaudio录音,再用wave写到文件,这里先用wave从文件中读入内存,再用pyaudio写到输出流中,由音响设备来播放声音。我们可以设置一个固定大小的chunk块来做缓冲。播放完毕后,需要将文件的输入流和音频的输出流关闭,以解除资源占用。
chunk=2014 def play(): wf=wave.open(r"01.wav",'rb') p=PyAudio() stream=p.open(format=p.get_format_from_width(wf.getsampwidth()),channels= wf.getnchannels(),rate=wf.getframerate(),output=True) while True: data=wf.readframes(chunk) if data=="":break stream.write(data) stream.close() p.terminate()
最后,只要在启动运行的时候,分别调用上述函数,就可以实现录音和播放的功能了。
if __name__ == '__main__': my_record() print('Over!') play()
版权声明本博客的文章除特别说明外均为原创,本人版权所有。欢迎转载,转载请注明作者及来源链接,谢谢。本文地址: https://blog.ailemon.net/2019/08/13/python-implement-audio-recorder-and-player/ All articles are under Attribution-NonCommercial-ShareAlike 4.0 |
WeChat Donate
Alipay Donate
发表回复