程式內容簡述:
使用Python程式實作簡單的語音識別程式,程式可以識別任意時間長度的語音,在語音輸入完成后,點擊回車就可以結束錄音,可進行任意時間段的語音識別,
該語音識別程式借助百度智能云提供的云應用進行語音識別,使用百度智能云的語音識別模塊識別語音之后回傳文本,將文本以文本檔案保存在磁盤中,
在進行語音識別程式之前需要在百度智能云上創建自己的語音識別應用,在程式中呼叫該應用進行語音識別,注冊百度智能云之后可以免費領取各種模塊的使用次數,然后創建相應的應用即可,
創建的應用結果如下:
博主創建的應用的重要資訊已擦出,在創建應用時如遇到不明白的地方歡迎提問,博主將盡快回復,
程式代碼如下:
import pyaudio
import time
import wave
import _thread
from aip import AipSpeech
class Recorder():
def __init__(self, chunk=1024, channels=1, rate=16000):
self.CHUNK = chunk
self.FORMAT = pyaudio.paInt16
self.CHANNELS = channels
self.RATE = rate
self._running = True
self._frames = []
def start(self):
_thread.start_new_thread(self.__recording, ())
def __recording(self):
self._running = True
self._frames = []
p = pyaudio.PyAudio()
stream = p.open(format=self.FORMAT,
channels=self.CHANNELS,
rate=self.RATE,
input=True,
frames_per_buffer=self.CHUNK)
while (self._running):
data = stream.read(self.CHUNK)
self._frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
def stop(self):
self._running = False
def save1(self, filename):
p = pyaudio.PyAudio()
if not filename.endswith(".wav"):
filename = filename + ".wav"
wf = wave.open(filename, 'wb')
wf.setnchannels(self.CHANNELS)
wf.setsampwidth(p.get_sample_size(self.FORMAT))
wf.setframerate(self.RATE)
wf.writeframes(b''.join(self._frames))
wf.close()
def record(self):
print('請按下回車鍵開始錄音:')
a = input()
if str.__len__(a)==0:
begin = time.time()
print("Start recording")
self.start()
print("請按下回車鍵結束錄音:")
b=input()
if str.__len__(b)==0:
print("Stop recording")
self.stop()
fina = time.time()
t = fina - begin
print('錄音時間為%ds' % t)
def positive(self):
print('開始樣本的錄制')
self.record()
self.save1("test2.wav")
def save2(result,filename):
if not filename.endswith(".txt"):
filename = filename + ".txt"
wf = open(filename, encoding='utf-8',mode='a+')
wf.writelines(result)
wf.writelines(['\n'])
wf.close()
def ASR():
rec = Recorder()
rec.positive()
print('識別中......')
APP_ID = '25.....'#自己創建的百度智能云語音識別應用的APPID
API_KEY = 'PSV4jja9................'#自己創建的百度智能云語音識別應用的API-key
SECRET_KEY = 'Aw59NW...............'#自己創建的百度智能云語音識別應用的secret_key
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
# 讀取檔案
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
# 識別本地檔案
res=client.asr(get_file_content('test2.wav'), 'wav', 16000, {'dev_pid': 1536,})
if res and res['err_no'] == 0:
result = res['result'][0]
print("識別結果為:")
print(result)
result2=res['result'][0]
save2(result2,'wenben.txt')
if __name__ == '__main__':
ASR()
程式運行結果如下:

由于免費試用的語音識別模塊識別精度比較差,所以對于比較復雜的語音識別可能會出現比較多的錯誤,但是對于標準的發音的語音識別還是比較準確地,
內容僅做交流學習使用,如存在錯誤請大家指正,歡迎大家一起交流學習,學習更多有用有趣的知識,喜歡博主的別忘了點贊哦!
關注博主,學習更多Python程式設計知識!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/414010.html
標籤:其他
上一篇:YOLOv5中的Focus層
