如何通过Python下载Resemble录音?代码报KeyError: 'item'求解
问题分析与解决方案
核心问题点
- 文件操作模式错误:用
'rb'(只读二进制)打开文件后执行write操作,会触发IO错误,只读模式不支持写入。 - API方法误用:你要生成AI语音(文本转语音),但误用了
Resemble.v2.recordings.create(该方法用于上传用户自有录音到平台),正确的方法应为Resemble.v2.synthesize.create。 - Response结构误判:代码假设返回结果包含
'item'键,但实际API返回结构与预期不符,直接取键导致KeyError。
修正后的代码
from resemble import Resemble Resemble.api_key('<MY API KEY>') def create_recording(): voice_uuid = '58be67d5-701b-40aa-b796-e753fae53993' name = 'recording' text = 'This is a test' is_active = True emotion = 'neutral' # 使用synthesize.create生成文本转语音内容 response = Resemble.v2.synthesize.create( voice_uuid=voice_uuid, text=text, name=name, is_active=is_active, emotion=emotion ) # 先打印完整响应,确认实际返回结构 print("API Response:", response) # 根据实际响应结构提取音频数据并写入文件(示例假设键为'audio',需根据实际调整) with open("test_recording.wav", 'wb') as output_file: output_file.write(response['audio']) create_recording()
额外说明
- 执行代码前先打印
response,确认API返回的实际键名(比如可能是'file'或嵌套在'recording'下),避免再次出现KeyError。 - 确认你的API Key拥有
synthesize接口的调用权限,且voice_uuid对应的语音资源属于你的账号。 - 若你确实需要上传自有录音(而非生成AI语音),则需保留
recordings.create,但要确保传入的file是合法的音频文件,且参数以关键字形式传递,同时根据官方文档调整响应提取逻辑。
内容的提问来源于stack exchange,提问作者Finn McKinley
相关产品推荐
相关产品推荐

