python調(diào)用百度語音識別api
最近在處理語音檢索相關(guān)的事。
其中用到語音識別,調(diào)用的是訊飛與百度的api,前者使用js是實(shí)現(xiàn),后者用python3實(shí)現(xiàn)(因?yàn)樽约菏褂胮ython)
環(huán)境:
python3.5
centos 7
流程
整個(gè)百度語音識別rest api 使用分為三部分:
1 (申請操作)創(chuàng)建應(yīng)用,獲取應(yīng)用的 API Key 以及 Secret Key。
2 (程序?qū)崿F(xiàn))通過已知的 應(yīng)用的 API Key 以及 Secret Key, 發(fā)送post 請求到 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 ,獲取識別結(jié)果.
以上過程參考百度語音開發(fā)文檔,或者網(wǎng)上的資料。
python實(shí)現(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****" # 自己申請的應(yīng)用
secret_key = "8439155b9db2040b4acd13b0c*****" # 自己申請的應(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 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)
同時(shí),獲取語音信息可以通過:
import scipy.io.wavfile filename = "two.wav" rate, signal = scipy.io.wavfile.read(filename=filename)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python實(shí)現(xiàn)爬取百度圖片的方法示例
這篇文章主要介紹了python實(shí)現(xiàn)爬取百度圖片的方法,涉及Python基于requests、urllib等模塊的百度圖片抓取相關(guān)操作技巧,需要的朋友可以參考下2019-07-07
Python利用字典和列表實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Python如何利用字典和列表實(shí)現(xiàn)一個(gè)簡易的學(xué)生信息管理系統(tǒng),文中詳細(xì)注釋,方便理解,需要的可以參考一下2022-06-06
Python人工智能學(xué)習(xí)PyTorch實(shí)現(xiàn)WGAN示例詳解
這篇文章主要為大家介紹了人工智能學(xué)習(xí)PyTorch實(shí)現(xiàn)WGAN的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11
卷積神經(jīng)網(wǎng)絡(luò)經(jīng)典模型及其改進(jìn)點(diǎn)學(xué)習(xí)匯總
這篇文章主要為大家介紹了卷積神經(jīng)網(wǎng)絡(luò)經(jīng)典模型及其改進(jìn)點(diǎn)學(xué)習(xí)匯總,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
python 獲取utc時(shí)間轉(zhuǎn)化為本地時(shí)間的方法
今天小編就為大家分享一篇python 獲取utc時(shí)間轉(zhuǎn)化為本地時(shí)間的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
解決pycharm的Python console不能調(diào)試當(dāng)前程序的問題
今天小編就為大家分享一篇解決pycharm的Python console不能調(diào)試當(dāng)前程序的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01

