调用百度语音识别api报错
#准备好APPID,APUKEY,SecretKey
#创建识别对象
#将识别功能封装成函数
#通过在线识别
import requests
from urllib.request import urlopen
from urllib.request import Request
import base64
import json
#获取Torken
#封装到函数
def get_token(Key,Secret):
url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='\
+Key+ '&client_secret='+Secret
response = requests.post(url = url)
result = response.json()
token = result['access_token']
return token
token = get_token('API_KEY,SECRET_KEY')
token
#token
#设置网址
host = 'http://vop.baidu.com/server_api'
#识别的文件是什么
file = 'test.wav'#文件名
Format = file[-3:]#格式
#将文件转码为base64,用打开的方式进行读取
data = open(file,'rb').read()
#获得结果后要重新编码为utf-8格式
base_data = base64.b64encode(data).decode('utf-8')
#获取数据长度
length =len(base_data)
#设置文件信息和参数
params={
"format":Format,
"rate":16000,#频率
"dev_pid":1537,#识别模式
"channel":1,#频道数
"token":token,
"cuid":"321221baidu_workshop",#(随便写点数字,变成唯一用户编码)id信息
"len":4096,#数据长度
"speech":"base_data",
}
#进行响应,获取结果
#传递参数(先将参数转化成json结构)
data = json.dumps(params,sort_keys = False)
#获取响应(先传递给网址,有头部信息也要传进去)
response = Request(host,data.encode('utf-8'))
#获取网页响应结果(url获取网页里的response)
result = urlopen(response)
#读取网页中的数据(读到字符串)
result = result.read().decode('utf-8')
#字符串转化成字典
print(eval(result)["result"][0])
& C:/Users/apple/python.exe c:/Users/apple/Desktop/work/work.py
File "", line 1
& C:/Users/apple/python.exe c:/Users/apple/Desktop/work/work.py
^
SyntaxError: invalid syntax