最近在處理語音檢索相關(guān)的事。
其中用到語音識(shí)別,調(diào)用的是訊飛與百度的api,前者使用js是實(shí)現(xiàn),后者用python3實(shí)現(xiàn)(因?yàn)樽约菏褂胮ython)
環(huán)境:
python3.5
centos 7
流程
整個(gè)百度語音識(shí)別rest api 使用分為三部分:
1 (申請(qǐng)操作)創(chuàng)建應(yīng)用,獲取應(yīng)用的 API Key 以及 Secret Key。
2 (程序?qū)崿F(xiàn))通過已知的 應(yīng)用的 API Key 以及 Secret Key, 發(fā)送post 請(qǐng)求到 https://openapi.baidu.com/oauth/2.0/token 獲取 token
3 (程序?qū)崿F(xiàn)) 通過上步驟獲取的 token,通過post, 發(fā)送相關(guān)的 語音信息 到 http://vop.baidu.com/server_api ,獲取識(shí)別結(jié)果.
以上過程參考百度語音開發(fā)文檔,或者網(wǎng)上的資料。
python實(shí)現(xiàn)
程序整體如下:
import requestsimport jsonimport uuidimport base64def get_token(): url = "https://openapi.baidu.com/oauth/2.0/token" grant_type = "client_credentials" api_key = "NzGBYD0jPFDqVT8VHRYa****" # 自己申請(qǐng)的應(yīng)用 secret_key = "8439155b9db2040b4acd13b0c*****" # 自己申請(qǐng)的應(yīng)用 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)
同時(shí),獲取語音信息可以通過:
import scipy.io.wavfilefilename = "two.wav"rate, signal = scipy.io.wavfile.read(filename=filename)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選