python实现录音小程序
程序员文章站
2022-11-14 23:02:05
本文为大家分享了python实现录音小程序的具体代码,供大家参考,具体内容如下
学习目标:掌握python的pyaudio扩展包和wave模块录制语音的方法
w...
本文为大家分享了python实现录音小程序的具体代码,供大家参考,具体内容如下
学习目标:掌握python的pyaudio扩展包和wave模块录制语音的方法
- wav音频:声道数,采样频率,量化位数
python wav包是自带的,pyaudio需要下载
pip3 install pyaudio
python读wav文件:
fp=wave.open('','rb') nf=fp.getnframes()#获取文件的采样点数量 print('sampwidth:',fp.getsampwidth()) print('framerate:',fp.getframerate()) print('channels:',fp.getnchannels()) f_len=nf*2#文件长度计算,每个采样2个字节 audio_data=fp.readframes(nf)
python写wav文件:
def save_wave_file(filename,data): '''save the date to the wavfile''' wf=wave.open(filename,'wb') wf.setnchannels(channels)#声道 wf.setsampwidth(sampwidth)#采样字节 1 or 2 wf.setframerate(framerate)#采样频率 8000 or 16000 wf.writeframes(b"".join(data))#https://*.com/questions/32071536/typeerror-sequence-item-0-expected-str-instance-bytes-found 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*20:#控制录音时间 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播放音频
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()
完整录音播放的demo
import wave from pyaudio import pyaudio,paint16 framerate=8000 num_samples=2000 channels=1 sampwidth=2 time=2 def save_wave_file(filename,data): '''save the date to the wavfile''' wf=wave.open(filename,'wb') wf.setnchannels(channels) wf.setsampwidth(sampwidth) wf.setframerate(framerate) wf.writeframes(b"".join(data)) wf.close() 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*20:#控制录音时间 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() 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()
更多用法详见
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。