国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現錄音小程序

2020-02-15 22:52:20
字體:
來源:轉載
供稿:網友

本文為大家分享了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://stackoverflow.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=2014def 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 wavefrom pyaudio import PyAudio,paInt16framerate=8000NUM_SAMPLES=2000channels=1sampwidth=2TIME=2def 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=2014def 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()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 鹤峰县| 德令哈市| 临汾市| 临潭县| 田东县| 甘德县| 化州市| 邵东县| 万年县| 阜宁县| 阿鲁科尔沁旗| 富源县| 亳州市| 远安县| 海晏县| 南京市| 哈巴河县| 晋州市| 从化市| 黄陵县| 铁岭市| 孙吴县| 新营市| 抚远县| 嘉峪关市| 桑日县| 汝州市| 临安市| 永善县| 巴林右旗| 惠安县| 七台河市| 尼木县| 临朐县| 来宾市| 澄迈县| 泗水县| 巩义市| 连江县| 伊春市| 镇安县|