python調用百度語音(語音識別-鬥地主語音記牌器)

1、概述

本篇簡要介紹百度語音語音識別的基本使用(實際上是鬥地主時想弄個記牌器又沒money,抓包什麼的又不會,只好搞語音識別的了)python

 

2、建立應用

 

打開百度語音官網產品與使用->語音識別->當即使用->建立應用app

出現以下頁面url

依照提示依次填寫,最終結果spa

(ps:我就想弄個記牌的,就起了個計數器的名)code

點右方的 ‘查看key’ 記下App ID,API Key,Secret Key。接下來要用到orm

 

 

須要安裝模塊 pip install baidu-aip pip install pyaudio

 

語音識別代碼blog

from aip import AipSpeech """ 你的 APPID AK SK """ APP_ID = '你記下的APP_ID' API_KEY = '你記下的API_KEY' SECRET_KEY = '你記下的SECRET_KEY' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) # 讀取文件 def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() # 識別本地文件 li=client.asr(get_file_content('01.pcm'), 'pcm', 8000, { 'lan': 'zh', }) print(li) # 從URL獲取文件識別 # client.asr('', 'pcm', 16000, { # 'url': 'http://121.40.195.233/res/16k_test.pcm', # 'callback': 'http://xxx.com/receive', # })

python錄音代碼ip

import wave from pyaudio import PyAudio,paInt16 framerate=8000 NUM_SAMPLES=2000 channels=1 sampwidth=2 TIME=2 def 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*5:#控制錄音時間 string_audio_data = stream.read(NUM_SAMPLES) my_buf.append(string_audio_data) count+=1 print('.') save_wave_file('01.pcm',my_buf) stream.close() chunk=2014 def play(): wf=wave.open(r"01.pcm",'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()

 

效果以下圖:文檔

 

幫助文檔:get

百度語音幫助文檔or手冊

 

 

 

 

3、後記

本代碼未徹底實現,有興趣可自行整理,玩鬥地主的時候聲音可能要大點,由於識別有時候會報3001錯誤,音頻質量過差,不過被打可別找我

相關文章
相關標籤/搜索