百度语音API使用(python实现之二)

昨天是原始PCM数据上传,响应太慢,profiling一番,发现是curl耗时,估计是音频数据上传耗时


于是改用speex压缩编码格式

#encoding=utf-8

import os
import time
import urllib2, pycurl
import base64
import json

TOKEN_PATH = '/home/wang/.speech.token'

## get access token by api key & secret key
def has_token():
    try:
        stat_info = os.stat(TOKEN_PATH)
    except OSError:
        return False
    if stat_info.st_size < 10: #invalid if too small
        return False
    db_ctime = stat_info.st_ctime
    create_date = time.strftime('%m', time.localtime(db_ctime))
    current_date = time.strftime('%m', time.localtime(time.time()))
    if current_date != create_date:
        return False   #old beyond 1 day, need update
    else:
        return True

def get_token():
    if has_token():
        fp = open(TOKEN_PATH, 'r')
        token = fp.readline().rstrip('\n')
        fp.close()
        return token
    apiKey = "FzxxxxxwY0SS"
    secretKey = "66xx5axxxb882a"

    auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey;

    res = urllib2.urlopen(auth_url)
    json_data = res.read()
    token = json.loads(json_data)['access_token']
    fp = open(TOKEN_PATH, 'w')
    fp.write(token)
    fp.close()
    return token

def dump_res(buf):
    fp = open('log_spx.log', 'w')
    fp.write(buf)
    fp.close()


## post audio to server
def use_cloud(token):
    fp = open('test.spx', 'rb')
    fp.seek(os.SEEK_END)
    f_len = fp.tell()
    audio_data = fp.read(f_len)

    cuid = "acxxxxxx677" #my xiaomi phone MAC
    srv_url = 'http://vop.baidu.com/server_api' + '?cuid=' + cuid + '&token=' + token
    http_header = [
        'Content-Type: audio/speex; rate=8000',
        'Content-Length: %d' % f_len
    ]

    c = pycurl.Curl()
    c.setopt(pycurl.URL, str(srv_url)) #curl doesn't support unicode
    #c.setopt(c.RETURNTRANSFER, 1)
    c.setopt(c.HTTPHEADER, http_header)   #must be list, not dict
    c.setopt(c.POST, 1)
    c.setopt(c.CONNECTTIMEOUT, 30)
    c.setopt(c.TIMEOUT, 30)
    c.setopt(c.WRITEFUNCTION, dump_res)
    c.setopt(c.POSTFIELDS, audio_data)
    c.setopt(c.POSTFIELDSIZE, f_len)
    c.perform() #pycurl.perform() has no return val

if __name__ == "__main__":
    token = get_token()
    use_cloud(token)

但是百度“识别失败”,考虑到我的麦克风太差,换用样例代码中的test.pcm压成speex格式再试,仍然“识别错误”,求教!

{"err_msg":"recognition error.","err_no":3301,"sn":"320487617001432001015"}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
好的,下面是一个简单的Python代码实现百度语音识别API的过程: 1. 安装Python SDK 首先需要安装百度语音识别APIPython SDK,可以使用以下命令: ``` pip install baidu-aip ``` 2. 导入SDK 在Python代码中使用以下代码导入SDK: ```python from aip import AipSpeech ``` 3. 设置API信息 在代码中设置API的相关信息,包括App ID、API Key和Secret Key: ```python APP_ID = 'Your App ID' API_KEY = 'Your API Key' SECRET_KEY = 'Your Secret Key' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) ``` 4. 读取语音文件 使用Python的`wave`库读取语音文件,可以使用以下代码: ```python import wave with wave.open('audio.wav', 'rb') as f: audio_data = f.readframes(f.getnframes()) ``` 这里的`'audio.wav'`是语音文件的路径,需要根据实际情况进行修改。 5. 调用API进行识别 使用以上设置的`client`对象调用API进行语音识别,可以使用以下代码: ```python result = client.asr(audio_data, 'wav', 16000, {'dev_pid': 1536}) ``` 这里的`audio_data`是上一步读取的语音文件数据,`'wav'`表示语音文件的格式,`16000`表示采样率,`{'dev_pid': 1536}`表示使用普通话识别模型。 6. 处理识别结果 最后根据API返回的结果进行处理,可以使用以下代码: ```python if result['err_no'] == 0: print(result['result'][0]) else: print('识别失败:', result['err_msg']) ``` 这里的`result['result'][0]`表示识别结果,`result['err_no']`表示错误码,如果为0表示识别成功,否则表示识别失败。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值