python语音识别代码_python实现百度语音识别api
时间: 2023-09-02 11:14:57 浏览: 94
以下是Python实现百度语音识别API的代码示例:
```
import urllib.request
import json
import base64
# 设置百度API的相关参数
baidu_server = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={your_client_id}&client_secret={your_client_secret}"
baidu_api = "https://vop.baidu.com/server_api"
client_id = "your_client_id"
client_secret = "your_client_secret"
# 获取Access Token
token_url = baidu_server.format(client_id, client_secret)
token_data = urllib.request.urlopen(token_url).read().decode('utf-8')
token_json = json.loads(token_data)
access_token = token_json['access_token']
# 设置音频文件路径
audio_file = r"path/to/audio/file.wav"
# 读取音频文件内容
with open(audio_file, "rb") as f:
speech = base64.b64encode(f.read()).decode('utf-8')
speech_length = len(speech)
# 设置请求头
headers = {
"Content-Type": "application/json",
}
# 设置请求体
data = {
"format": "wav",
"rate": 16000,
"dev_pid": 1536,
"speech": speech,
"len": speech_length,
"cuid": "your_client_id",
"token": access_token,
}
# 发送POST请求
req = urllib.request.Request(url=baidu_api, data=json.dumps(data).encode('utf-8'), headers=headers)
result = urllib.request.urlopen(req).read().decode('utf-8')
# 解析API返回结果
result_json = json.loads(result)
if result_json["err_no"] == 0:
print(result_json["result"][0])
else:
print(result_json["err_msg"])
```
请注意,上述代码中的 `your_client_id` 和 `your_client_secret` 需要替换为您在百度AI开放平台中创建的应用的对应参数。此外,上述代码中的音频文件格式必须为wav格式,采样率为16000Hz,且音频时长不超过60秒。
阅读全文