云萌主云应用官方论坛

标题: 百度语音识别API的python使用示例 [打印本页]

作者: 骑单车的小女孩    时间: 2016-12-30 00:35
标题: 百度语音识别API的python使用示例

来源:http://www.open-open.com/code/view/1431932360224
百度给的样例程序,不论C还是Java版,都分为method1和method2两种
前者称为隐式(post的是json串,音频数据编码到json里),后者称为显式(post的就是音频数据)

一开始考虑到python wave包处理的都是“字符串”,担心跟C语言的数组不一致,所以选择低效但保险的method1,
即先将音频数据base64编码,再加上采样率、通道数等信息汇集成dict,最后总体编码成json串
结果老是报:
3300 输入参数不正确
先后试过urllib2和pycurl包,都是上面情况
不得已换用method2,成功(看来wave包对音频的存储并不是“字符串”)
  1. #encoding=utf-8  
  2.       
  3.     import wave  
  4.     import urllib, urllib2, pycurl  
  5.     import base64  
  6.     import json  
  7.     ## get access token by api key & secret key  
  8.       
  9.     def get_token():  
  10.         apiKey = "xxxxxxxx"  
  11.         secretKey = "xxxxxxxxx"  
  12.       
  13.         auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey;  
  14.       
  15.         res = urllib2.urlopen(auth_url)  
  16.         json_data = res.read()  
  17.         return json.loads(json_data)['access_token']  
  18.       
  19.     def dump_res(buf):  
  20.         print buf  
  21.       
  22.       
  23.     ## post audio to server  
  24.     def use_cloud(token):  
  25.         fp = wave.open('vad_0.wav', 'rb')  
  26.         nf = fp.getnframes()  
  27.         f_len = nf * 2  
  28.         audio_data = fp.readframes(nf)  
  29.       
  30.         cuid = "xxxxxxxxxx" #my xiaomi phone MAC  
  31.         srv_url = 'http://vop.baidu.com/server_api' + '?cuid=' + cuid + '&token=' + token  
  32.         http_header = [  
  33.             'Content-Type: audio/pcm; rate=8000',  
  34.             'Content-Length: %d' % f_len  
  35.         ]  
  36.       
  37.         c = pycurl.Curl()  
  38.         c.setopt(pycurl.URL, str(srv_url)) #curl doesn't support unicode  
  39.         #c.setopt(c.RETURNTRANSFER, 1)  
  40.         c.setopt(c.HTTPHEADER, http_header)   #must be list, not dict  
  41.         c.setopt(c.POST, 1)  
  42.         c.setopt(c.CONNECTTIMEOUT, 30)  
  43.         c.setopt(c.TIMEOUT, 30)  
  44.         c.setopt(c.WRITEFUNCTION, dump_res)  
  45.         c.setopt(c.POSTFIELDS, audio_data)  
  46.         c.setopt(c.POSTFIELDSIZE, f_len)  
  47.         c.perform() #pycurl.perform() has no return val  
  48.       
  49.     if __name__ == "__main__":  
  50.         token = get_token()  
  51.         use_cloud(token)
复制代码






欢迎光临 云萌主云应用官方论坛 (https://www.yunmengzhu.com/) Powered by Discuz! X3.4