项目二十四--百度云语音

来自Microduino Wikipedia
547146209@qq.com讨论 | 贡献2016年2月17日 (三) 08:39的版本 安装pip
跳转至: 导航搜索

百度语音,是百度推出的永久免费智能语音开放平台,百度语音官网http://yuyin.baidu.com/ 本项目是在microWRT上通过http请求的方式,使用REST API来访问百度的服务器进行语音识别与语音合成。 使用的语言为python

材料准备

MicroWRT

MicroWRT HUB 扩展板

tf卡

实现步骤

安装python

参见wiki教程第八课--MicroWRT SD卡/U盘使用

安装pip

首先安装setuptools,下载地址下载 将下载后的zip文件使用winscp工具传到MicroWRT上 在MicroWRT,解压

unzip setuptools-18.6.1.zip
cd setuptools-18.6.1
python setup.py install

安装完setuptools,安装pip

easy_install pip

安装所需要的python库

本项目中使用了requests库进行http请求 使用pip安装requests

pip install requests

申请在线接口

参见百度官方的接入流程 http://yuyin.baidu.com/docs/detail/147

示例程序

语音识别示例程序,本示例中是识别同目录下的一个demo.wav的音频文件

#encoding=utf-8
import sys  
reload(sys)  
sys.setdefaultencoding('utf8') 
import requests
import json
import base64
import wave

apiKey = "8FoGgqyhQyGGGoz6iNbZl4Wo"      		#需要换成自己申请的
secretKey = "ba00c27a164dcdeb98038d1a08dfbe85" 	#需要换成自己申请的

#获取认证需要的token
auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey;
r = requests.get(auth_url)
json_data = r.text
token =  json.loads(json_data)["access_token"]

#打开声音文件
fp = wave.open('demo.wav', 'rb')
nf = fp.getnframes()
f_len = nf * 2
audio_data = fp.readframes(nf)

#进行语音识别请求
http_header = {
        'Content-Type': 'audio/pcm; rate=16000',
        'Content-Length': f_len
    }
cuid = "microduino"
url = 'http://vop.baidu.com/server_api' + '?cuid=' + cuid + '&token=' + token
print url
r = requests.post(url,data = audio_data, headers = http_header)

#中文显示结果
print r.text.encode('gb18030')

执行结果如下

{"corpus_no":"6251794034343536890","err_msg":"success.","err_no":0,"result":["语音识别显示音频,"],"sn":"47325544061455609229"}