python调用百度ai语音识别代码
时间: 2023-08-18 18:04:15 浏览: 64
你可以使用Python的requests库来调用百度AI语音识别API。以下是一个示例代码:
```python
import requests
import json
# 百度AI语音识别API接口地址
url = "http://vop.baidu.com/server_api"
# 申请的百度AI语音识别应用的API Key和Secret Key
api_key = "your_api_key"
secret_key = "your_secret_key"
# 读取语音文件内容
with open("test.wav", "rb") as f:
speech_data = f.read()
# 设置请求头
headers = {
"Content-Type": "audio/wav;rate=16000",
"Content-Length": str(len(speech_data))
}
# 设置请求参数
params = {
"format": "wav",
"rate": 16000,
"dev_pid": 1536, # 普通话(输入法模型)
"cuid": "your_cuid", # 自定义用户标识,可为空
"token": "your_access_token", # Access Token,可为空
"speech": speech_data,
"len": len(speech_data)
}
# 生成签名
import hashlib
import base64
import time
cur_time = str(int(time.time()))
tmp = api_key + cur_time
sign = hashlib.md5(tmp.encode("utf-8")).hexdigest()
sign = base64.b64encode(sign.encode("utf-8")).decode("utf-8")
# 发送POST请求
params["sign"] = sign
params["apikey"] = api_key
params["timestamp"] = cur_time
response = requests.post(url, data=params, headers=headers)
# 解析响应数据
result = json.loads(response.text)
if result["err_msg"] == "success.":
print(result["result"][0])
else:
print(result["err_msg"])
```
其中,`test.wav`是需要识别的语音文件,`api_key`和`secret_key`是你申请的百度AI语音识别应用的API Key和Secret Key,`your_cuid`和`your_access_token`分别是自定义用户标识和Access Token,可为空。如果需要识别其他语种或方言,可以修改`dev_pid`参数。具体参数说明可以参考[百度AI语音识别API文档](https://ai.baidu.com/docs#/ASR-Online-Python-SDK/top)。
相关推荐

















