Python結合百度語音識別實現實時翻譯軟件的實現
pip install PyAudiopip install SpeechRecognitionpip install baidu-aippip install Wavepip install Wheelpip install Pyinstaller二、百度官網申請服務
import pyaudioimport wavefrom aip import AipSpeechimport time# 用Pyaudio庫錄制音頻# out_file:輸出音頻文件名# rec_time:音頻錄制時間(秒)def audio_record(out_file, rec_time): CHUNK = 1024 FORMAT = pyaudio.paInt16 # 16bit編碼格式 CHANNELS = 1 # 單聲道 RATE = 16000 # 16000采樣頻率 p = pyaudio.PyAudio() # 創建音頻流 stream = p.open(format=FORMAT, # 音頻流wav格式 channels=CHANNELS, # 單聲道 rate=RATE, # 采樣率16000 input=True, frames_per_buffer=CHUNK) print('開始記錄語音{0}秒后開始識別...'.format(rec_time)) frames = [] # 錄制的音頻流 # 錄制音頻數據 for i in range(0, int(RATE / CHUNK * rec_time)): data = stream.read(CHUNK) frames.append(data) # 錄制完成 stream.stop_stream() stream.close() p.terminate() print('結束識別') # 保存音頻文件 wf = wave.open(out_file, ’wb’) wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(b’’.join(frames)) wf.close()def audio_recog(recogFile): # 讀取文件 def get_file_content(filePath): with open(filePath, ’rb’) as fp: return fp.read() # 識別本地文件 result = client.asr(get_file_content(recogFile), ’wav’, 16000, {’dev_pid’: 1537,}) return resultdef write_file(file,text): import time time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) f = open(file, ’a’) f.write(time+’:’+text+’n’) f.close()audioFile='audio.wav'textFile='識別結果.txt'''' 你的 APPID AK SK '''APP_ID = ’你的APP_ID’API_KEY = ’你的API_KEY’SECRET_KEY = ’你的SECRET_KEY’client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)if __name__ == ’__main__’: while True: audio_record(audioFile, 5) textResult = audio_recog('audio.wav') if textResult[’err_msg’] =='success.': print(textResult[’result’]) write_file(textFile,str(textResult[’result’]))四、打包成軟件
進入到目錄執行下面命令:
pyinstaller -F main.py
到此這篇關于Python結合百度語音識別實現實時翻譯軟件的實現的文章就介紹到這了,更多相關Python 實時翻譯軟件內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: