python調用百度語音識別api
最近在處理語音檢索相關的事。
其中用到語音識別,調用的是訊飛與百度的api,前者使用js是實現(xiàn),后者用python3實現(xiàn)(因為自己使用python)
環(huán)境:
python3.5
centos 7
流程
整個百度語音識別rest api 使用分為三部分:
1 (申請操作)創(chuàng)建應用,獲取應用的 API Key 以及 Secret Key。
2 (程序實現(xiàn))通過已知的 應用的 API Key 以及 Secret Key, 發(fā)送post 請求到 https://openapi.baidu.com/oauth/2.0/token 獲取 token
3 (程序實現(xiàn)) 通過上步驟獲取的 token,通過post, 發(fā)送相關的 語音信息 到 http://vop.baidu.com/server_api ,獲取識別結果.
以上過程參考百度語音開發(fā)文檔,或者網(wǎng)上的資料。
python實現(xiàn)
程序整體如下:
import requests
import json
import uuid
import base64
def 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 token
def 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 = 8000
token = get_token()
recognize(signal, rate, token)
同時,獲取語音信息可以通過:
import scipy.io.wavfile filename = "two.wav" rate, signal = scipy.io.wavfile.read(filename=filename)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python劃分數(shù)組為連續(xù)數(shù)字集合的練習
這篇文章主要給大家分享的是Python劃分數(shù)組為連續(xù)數(shù)字集合的練習,下面文章首先對問題進行詳細描述,在根據(jù)問題提出解決方案,內容詳細,需要的朋友可以參考一下,希望對你有所幫助2021-11-11
Pearson相關系數(shù)和Spearman相關系數(shù)的區(qū)別及說明
這篇文章主要介紹了Pearson相關系數(shù)和Spearman相關系數(shù)的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
Python數(shù)據(jù)分析之pandas函數(shù)詳解
這篇文章主要介紹了Python數(shù)據(jù)分析之pandas函數(shù)詳解,文中有非常詳細的代碼示例,對正在學習python的pandas函數(shù)的小伙伴們有很好地幫助,需要的朋友可以參考下2021-04-04
Python編程實現(xiàn)下載器自動爬取采集B站彈幕示例
這篇文章主要介紹了使用Python編程來實現(xiàn)一個下載器可以自動爬取采集B站彈幕的示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2021-10-10
pytorch之pytorch?hook和關于pytorch?backward過程問題
這篇文章主要介紹了pytorch之pytorch?hook和關于pytorch?backward過程問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09

