python的pyaudio可以進(jìn)行錄音,播放,生成wav文件等等,WAVE是錄音時(shí)用的標(biāo)準(zhǔn)的WINDOWS文件格式,文件的擴(kuò)展名為WAV,數(shù)據(jù)本身的格式為PCM或壓縮型,屬于無損音樂格式的一種。在我們研究語音識(shí)別,自然語言處理的過程中,常常會(huì)使用到它,比如我們調(diào)用百度語音識(shí)別所以我們首先研究一下pyaudio庫的安裝與使用。
成都創(chuàng)新互聯(lián)公司是一家以重慶網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)、品牌設(shè)計(jì)、軟件運(yùn)維、seo優(yōu)化排名、小程序App開發(fā)等移動(dòng)開發(fā)為一體互聯(lián)網(wǎng)公司。已累計(jì)為成都垃圾桶等眾行業(yè)中小客戶提供優(yōu)質(zhì)的互聯(lián)網(wǎng)建站和軟件開發(fā)服務(wù)。安裝:
pip install pyaudio
調(diào)用pyaudio使用麥克風(fēng)錄制聲音:
python中的pyaudio庫可以直接通過麥克風(fēng)錄制聲音,我們可以通過調(diào)用該庫,獲取到wav測試語音。 具體代碼如下所示:
#!/usr/bin/python3 # -*- coding: utf-8 -*- from pyaudio import PyAudio, paInt16 import numpy as np from datetime import datetime import wave class recoder: NUM_SAMPLES = 2000 #pyaudio內(nèi)置緩沖大小 SAMPLING_RATE = 8000 #取樣頻率 LEVEL = 500 #聲音保存的閾值 COUNT_NUM = 20 #NUM_SAMPLES個(gè)取樣之內(nèi)出現(xiàn)COUNT_NUM個(gè)大于LEVEL的取樣則記錄聲音 SAVE_LENGTH = 8 #聲音記錄的最小長度:SAVE_LENGTH * NUM_SAMPLES 個(gè)取樣 TIME_COUNT = 60 #錄音時(shí)間,單位s Voice_String = [] def savewav(self,filename): wf = wave.open(filename, 'wb') wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(self.SAMPLING_RATE) wf.writeframes(np.array(self.Voice_String).tostring()) # wf.writeframes(self.Voice_String.decode()) wf.close() def recoder(self): pa = PyAudio() stream = pa.open(format=paInt16, channels=1, rate=self.SAMPLING_RATE, input=True, frames_per_buffer=self.NUM_SAMPLES) save_count = 0 save_buffer = [] time_count = self.TIME_COUNT while True: time_count -= 1 # print time_count # 讀入NUM_SAMPLES個(gè)取樣 string_audio_data = stream.read(self.NUM_SAMPLES) # 將讀入的數(shù)據(jù)轉(zhuǎn)換為數(shù)組 audio_data = np.fromstring(string_audio_data, dtype=np.short) # 計(jì)算大于LEVEL的取樣的個(gè)數(shù) large_sample_count = np.sum( audio_data > self.LEVEL ) print(np.max(audio_data)) # 如果個(gè)數(shù)大于COUNT_NUM,則至少保存SAVE_LENGTH個(gè)塊 if large_sample_count > self.COUNT_NUM: save_count = self.SAVE_LENGTH else: save_count -= 1 if save_count < 0: save_count = 0 if save_count > 0 : # 將要保存的數(shù)據(jù)存放到save_buffer中 #print save_count > 0 and time_count >0 save_buffer.append( string_audio_data ) else: #print save_buffer # 將save_buffer中的數(shù)據(jù)寫入WAV文件,WAV文件的文件名是保存的時(shí)刻 #print "debug" if len(save_buffer) > 0 : self.Voice_String = save_buffer save_buffer = [] print("Recode a piece of voice successfully!") return True if time_count==0: if len(save_buffer)>0: self.Voice_String = save_buffer save_buffer = [] print("Recode a piece of voice successfully!") return True else: return False if __name__ == "__main__": r = recoder() r.recoder() r.savewav("test.wav")