调用讯飞开放平台语音转写demo,用python写一个调用文件夹下的所有音频文件对其逐一进行语音转写输出成TXT文本保存
时间: 2024-05-07 08:15:15 浏览: 20
以下是Python代码:
```python
import os
import requests
import json
# 讯飞开放平台的API地址和密钥
api_url = 'http://api.xfyun.cn/v1/service/v1/iat'
api_key = 'your_api_key'
api_secret = 'your_api_secret'
# 获取音频文件列表
audio_folder = 'audio_folder_path'
audio_files = [os.path.join(audio_folder, f) for f in os.listdir(audio_folder) if f.endswith('.wav')]
# 逐一处理音频文件,调用讯飞开放平台API进行语音转写
for audio_file in audio_files:
print('Transcribing {}'.format(audio_file))
with open(audio_file, 'rb') as f:
audio_data = f.read()
audio_len = len(audio_data)
audio_base64 = str(base64.b64encode(audio_data), 'utf-8')
param_data = {
'engine_type': 'sms16k',
'aue': 'raw',
'audio': audio_base64,
'audio_len': audio_len
}
x_param = base64.b64encode(json.dumps(param_data).replace(' ', '').encode('utf-8')).decode('utf-8')
x_time = int(int(round(time.time() * 1000)) / 1000)
x_checksum = hashlib.md5((api_key + str(x_time) + x_param).encode('utf-8')).hexdigest()
headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'X-Appid': api_key,
'X-CurTime': str(x_time),
'X-Param': x_param,
'X-CheckSum': x_checksum,
}
res = requests.post(api_url, headers=headers, data=param_data)
res_data = json.loads(res.text)
if res_data['code'] == '0':
txt_file = os.path.splitext(audio_file)[0] + '.txt'
with open(txt_file, 'w', encoding='utf-8') as f:
f.write(res_data['data'])
print('Transcription saved to {}'.format(txt_file))
else:
print('Error: {}'.format(res_data['desc']))
```
需要注意的是,需要替换代码中的 `your_api_key` 和 `your_api_secret` 为真实的讯飞开放平台API密钥。此外,需要安装 `requests`、`json`、`base64` 和 `hashlib` 库。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)