python调用百度语音识别api

yipeiwu_com5年前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

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)

同时,获取语音信息可以通过:

import scipy.io.wavfile
filename = "two.wav"
rate, signal = scipy.io.wavfile.read(filename=filename)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Pandas GroupBy对象 索引与迭代方法

如下所示: import pandas as pd df = pd.DataFrame({'性别' : ['男', '女', '男', '女', '男', '女',...

python_opencv用线段画封闭矩形的实例

如下所示: def draw_circle(event,x,y,flags,param): global ix,iy,drawing,mode,start_x,start_y...

python的re模块应用实例

本文实例讲述了python的re模块应用。是非常重要的应用技巧。分享给大家供大家参考。 具体方法如下: import re # match_object = re.match('...

Python3.5装饰器典型案例分析

本文实例讲述了Python3.5装饰器。分享给大家供大家参考,具体如下: #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:...

Python 获取windows桌面路径的5种方法小结

这里介绍了5中python获取window桌面路径的方法,获取这个路径有什么用呢?一般是将程序生成的文档输出到桌面便于查看编辑。 前两个方法是通过注册表来获取当前windows桌面绝对路...