基于http的百度语音 REST api

什么是REST api?
-- REpresentational State Transfer
REST api是基于http请求的一种api,就百度语音识别的实例来说,经过百度提供的url加上通过编码的音频文件,向百度服务器发出请求,而后百度服务器返回识别的内容。结束。php

优势java

不受平台限制(我在树莓派上操做的)
代码简单

缺点:python

依赖网络
对要识别的音频格式要求高

百度语音REST api 支持的语言java、php、python、c# 、Node.js。下面分享一个python2.7版的实例
1.先去注册开发者帐号,新建应用,得到APP_ID,API_KEY,SECRET_KEY
2.安装SDKjson

安装使用SDK有以下方式:
若是已安装pip,执行pip install baidu-aip便可。
若是已安装setuptools,执行python setup.py install便可

3.安装完了看代码
语音合成c#

# -*- coding: UTF-8 -*-
from aip import AipSpeech
# 定义常量
APP_ID = '9****418'
API_KEY = 'uXmKYE0zX67****kGxO8c0'
SECRET_KEY = 'ba7c43158****2d0d180c80f132a'
# 初始化AipSpeech对象

aipSpeech = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
result  = aipSpeech.synthesis(' 一二三四五六七八九十', 'zh', 1, {
    'vol': 5,
})
# 识别正确返回语音二进制 错误则返回dict 参照下面错误码
if not isinstance(result, dict):
    with open('8k.wav', 'wb') as f:
        f.write(result)

完了,就这些,synthesis()方法的第一个参数是要合成的文字,open()方法的第一个参数是合成后的文件名加后缀,其余没啥。api

语音识别
语音识别分为显式和隐式。实测效果同样。
我搞不清哪一个叫显式哪一个叫隐式了
一个是这样的服务器

# -*- coding: UTF-8 -*-
from aip import AipSpeech
import json
# 定义常量
APP_ID = '99***418'
API_KEY = 'uXmKY*****kcbCWkGxO8c0'
SECRET_KEY = 'ba7c43158*******d0d180c80f132a'
# 初始化AipSpeech对象
aipSpeech = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

# 读取文件
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()
# 识别本地文件
result = aipSpeech.asr(get_file_content('8k.amr'), 'amr', 8000, {
    'lan': 'zh',
})
json_result = json.dumps(result)
strtestObj = json.loads(json_result)
#print strtestObj
lists = strtestObj["result"]
print "识别结果:".decode('utf-8').encode('gbk'),lists[0]

get_file_content()方法的参数是要上传的音频文件名加后缀(音频格式),
asr()方法的第二个参数是音频格式,第二个参数是采样率,仅支持 8000 或者 16000网络

另外一个是这样的app

# -*- coding: UTF-8 -*-
import base64
import urllib2
import urllib
import json
import wave
def get_token():
    URL = 'http://openapi.baidu.com/oauth/2.0/token'
    _params = urllib.urlencode({'grant_type': 'client_credentials',
                                'client_id': 'uXmKYE0z*****cbCWkGxO8c0',
                                'client_secret': 'ba7c43158dca*****2d0d180c80f132a'})
    _res = urllib2.Request(URL, _params)
    _response = urllib2.urlopen(_res)
    _data = _response.read()
    _data = json.loads(_data)
    return _data['access_token']
# 读取文件
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

def wav_to_text(wav_file):
    try:
        speech_data= get_file_content(wav_file)
        speech_base64=base64.b64encode(speech_data).decode('utf-8')
        speech_length=len(speech_data)

    except IOError:
        print u'文件错误!'
        return
    data = {"format": "wav",
            "token": get_token(),
            "len": speech_length,
            "rate": 8000,
            "speech": speech_base64,
            "cuid": "74-D0-2B-78-BF-AA",
            "channel": 1}
    data = json.dumps(data)
    res = urllib2.Request('http://vop.baidu.com/server_api',
                            data,
                            {'content-type': 'application/json'})
    response = urllib2.urlopen(res)
    res_data = json.loads(response.read())
    print res_data ['result'][0]

if __name__ == '__main__':
    wav_to_text('1.wav')

“duang” 拉么多!仍是果断选第一种,不过仍是先简单介绍一下吧:思路是这样的:python2.7

先根据API_KEY和SECRET_KEY得到token,
而后压缩音频文件 b64encode()方法之类操做
最后封装url后Request()去请求.
相关文章
相关标签/搜索