python调用百度语音识别api-创新互联

最近在处理语音检索相关的事。
其中用到语音识别,调用的是讯飞与百度的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 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)

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


当前文章:python调用百度语音识别api-创新互联
链接分享:http://myzitong.com/article/dhiphp.html