資源簡介
python代碼實現(xiàn)錄音,可以生成標(biāo)準(zhǔn)格式的wav文件,方便使用,可以進(jìn)一步實現(xiàn)調(diào)用該百度API實現(xiàn)轉(zhuǎn)錄
代碼片段和文件信息
#!/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個取樣之內(nèi)出現(xiàn)COUNT_NUM個大于LEVEL的取樣則記錄聲音
????SAVE_LENGTH?=?8?????????#聲音記錄的最小長度:SAVE_LENGTH?*?NUM_SAMPLES?個取樣
????TIME_COUNT?=?60?????#錄音時間,單位s
????Voice_String?=?[]
????def?savewav(selffilename):
????????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個取樣
????????????string_audio_data?=?stream.read(self.NUM_SAMPLES)
????????????#?將讀入的數(shù)據(jù)轉(zhuǎn)換為數(shù)組
????????????audio_data?=?np.fromstring(string_audio_data?dtype=np.short)
????????????#
評論
共有 條評論