1. 程式人生 > >百度語音識別api呼叫 python

百度語音識別api呼叫 python

最近在處理語音檢索相關的事。
其中用到語音識別,呼叫的是訊飛與百度的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

python實現

程式整體如下:

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)

這裡寫圖片描述