Flask调用Azure文本转语音REST API返回空音频文件问题排查
问题解决:Flask调用Azure Text to Speech API返回空音频文件
问题现象
直接通过Postman调用Azure Text to Speech REST API可获取正常播放的音频文件,但通过Flask接口转发调用时,返回空音频文件,同时触发以下报错:
<Response [200]> Debugging middleware caught exception in streamed response at a point where response headers were already sent. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/werkzeug/wsgi.py", line 576, in __next__ data = self.file.read(self.buffer_size) AttributeError: 'Response' object has no attribute 'read'
报错原因
Flask的send_file()函数要求传入类文件对象(支持read()方法)或文件路径,但代码中直接传入了requests库的Response对象,该对象本身不具备read()方法,导致无法正确读取音频数据返回给客户端。
修复方案
- 从requests响应中提取二进制音频数据(
response.content) - 将二进制数据包装为
BytesIO对象(该对象支持read()方法,符合send_file()的要求) - 可选:添加响应状态码检查,确保Azure API调用成功
修改后的代码示例
from flask import send_file from io import BytesIO import requests def call_azure_cognitive_api(text): token = get_token() cognitive_service_url = 'https://eastus.tts.speech.microsoft.com/cognitiveservices/v1' headers = { 'Authorization': 'Bearer %s' % token, 'X-Microsoft-OutputFormat': 'audio-16khz-32kbitrate-mono-mp3', 'Content-Type': 'application/ssml+xml' } data = """<speak version='1.0' xml:lang='en-US'><voice xml:lang='en-US' xml:gender='Male' name='en-US-ChristopherNeural'> Microsoft Speech Service Text-to-Speech API </voice></speak>""" response = requests.post(cognitive_service_url, data=data, headers=headers) print(response) # 检查Azure API调用是否成功 if response.status_code != 200: # 可根据需求返回错误响应,比如return "API调用失败", 500 pass # 将音频二进制数据包装为BytesIO对象 audio_io = BytesIO(response.content) # 设置文件指针到起始位置 audio_io.seek(0) return send_file(audio_io, mimetype="audio/mpeg", download_name="ajinkya.mp3")
内容的提问来源于stack exchange,提问作者Ajinkya Gadgil
相关产品推荐
相关产品推荐

