如何用Python实现Flask接口调用pyttsx3返回MP3字节数组
实现Flask API将文本转换为MP3字节数组返回
步骤1:安装依赖
先安装所需的Python库:
pip install flask pyttsx3
注意:Windows系统可能需额外安装pywin32;Linux/macOS需安装对应语音引擎依赖,比如Linux的espeak、macOS的系统自带say命令
步骤2:编写Flask API代码
核心思路是用内存字节流替代本地文件,让pyttsx3直接将语音输出写入内存,再把字节数据返回给客户端:
from flask import Flask, request, send_file import pyttsx3 from io import BytesIO app = Flask(__name__) def text_to_speech_bytes(text): # 初始化语音引擎 engine = pyttsx3.init() # 可选:配置语音参数 voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) # 选择发音人 engine.setProperty('rate', 150) # 设置语速 engine.setProperty('volume', 0.9) # 设置音量 # 创建内存字节流 audio_stream = BytesIO() # 将语音写入内存流(pyttsx3支持文件对象作为输出目标) engine.save_to_file(text, audio_stream) engine.runAndWait() # 将流指针移至开头,准备读取 audio_stream.seek(0) return audio_stream @app.route('/text-to-mp3', methods=['POST']) def text_to_mp3(): # 获取请求中的文本参数 data = request.get_json() if not data or 'text' not in data: return {'error': '缺少"text"参数'}, 400 text = data['text'] try: audio_stream = text_to_speech_bytes(text) # 返回MP3字节流,设置正确的内容类型 return send_file( audio_stream, mimetype='audio/mpeg', as_attachment=False, download_name='speech.mp3' ) except Exception as e: return {'error': str(e)}, 500 if __name__ == '__main__': app.run(debug=True)
关键细节说明
- 使用
BytesIO避免磁盘IO操作,提升接口响应效率 engine.save_to_file支持直接写入文件对象,无需生成本地临时文件send_file负责将内存中的音频字节流以audio/mpeg类型返回给客户端
测试API
可以用curl命令快速测试:
curl -X POST -H "Content-Type: application/json" -d '{"text": "这是一段文本转语音的测试内容"}' http://localhost:5000/text-to-mp3 --output test.mp3
也可以用Postman发送POST请求,携带JSON参数{"text": "你的测试文本"},响应会直接返回MP3音频数据。
注意事项
- pyttsx3依赖系统语音引擎,不同系统需确保依赖安装完整:
- Windows:默认自带SAPI5引擎,无需额外配置
- Linux:需安装
espeak和ffmpeg,可执行sudo apt-get install espeak ffmpeg - macOS:系统自带
say命令,可直接使用
- 若默认输出格式不是MP3,可借助
ffmpeg对音频流进行转码扩展实现
内容的提问来源于stack exchange,提问作者raju
相关产品推荐
相关产品推荐

