最近在處理語音檢索相關的事。
其中用到語音識別,調用的是訊飛與百度的api,前者使用js是實現,后者用python3實現(因為自己使用python)
環境:
python3.5
centos 7
流程
整個百度語音識別rest api 使用分為三部分:
1 (申請操作)創建應用,獲取應用的 API Key 以及 Secret Key。
2 (程序實現)通過已知的 應用的 API Key 以及 Secret Key, 發送post 請求到 https://openapi.baidu.com/oauth/2.0/token 獲取 token
3 (程序實現) 通過上步驟獲取的 token,通過post, 發送相關的 語音信息 到 http://vop.baidu.com/server_api ,獲取識別結果.
以上過程參考百度語音開發文檔,或者網上的資料。
python實現
程序整體如下:
import requestsimport jsonimport uuidimport base64def get_token(): url = "https://openapi.baidu.com/oauth/2.0/token" grant_type = "client_credentials" api_key = "NzGBYD0jPFDqVT8VHRYa****" # 自己申請的應用 secret_key = "8439155b9db2040b4acd13b0c*****" # 自己申請的應用 data = {'grant_type': 'client_credentials', 'client_id': api_key, 'client_secret': secret_key} r = requests.post(url, data=data) token = json.loads(r.text).get("access_token") return tokendef recognize(sig, rate, token): url = "http://vop.baidu.com/server_api" speech_length = len(sig) speech = base64.b64encode(sig).decode("utf-8") mac_address = uuid.UUID(int=uuid.getnode()).hex[-12:] rate = rate data = { "format": "wav", "lan": "zh", "token": token, "len": speech_length, "rate": rate, "speech": speech, "cuid": mac_address, "channel": 1, } data_length = len(json.dumps(data).encode("utf-8")) headers = {"Content-Type": "application/json", "Content-Length": data_length} r = requests.post(url, data=json.dumps(data), headers=headers) print(r.text)filename = "two.wav"signal = open(filename, "rb").read()rate = 8000token = get_token()recognize(signal, rate, token)
同時,獲取語音信息可以通過:
import scipy.io.wavfilefilename = "two.wav"rate, signal = scipy.io.wavfile.read(filename=filename)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。
新聞熱點
疑難解答