feat: AI回复语音播放功能(Edge TTS)

This commit is contained in:
2026-04-28 17:28:07 +08:00
parent 60db170c0d
commit 7de13ffc6d
4 changed files with 252 additions and 7 deletions

View File

@@ -4,7 +4,7 @@ AI Chat App - 后台管理服务
端口: 19021 (与前端同一端口)
"""
from flask import Flask, jsonify, request, send_from_directory
from flask import Flask, jsonify, request, send_from_directory, Response
from flask_cors import CORS
import os
import json
@@ -12,6 +12,8 @@ import sqlite3
from datetime import datetime
import hashlib
import base64
import asyncio
import edge_tts
app = Flask(__name__, static_folder='../www')
CORS(app)
@@ -273,6 +275,8 @@ def init_db():
('app_description', '提供智能对话、多种智能体服务', '应用简介'),
('privacy_policy_url', '', '隐私政策链接'),
('user_agreement_url', '', '用户协议链接'),
('tts_provider', 'edge', 'TTS方案'),
('tts_voice', 'zh-CN-XiaoxiaoNeural', 'TTS语音'),
]
for key, value, desc in default_configs:
cursor.execute('INSERT INTO system_configs (key, value, description) VALUES (?, ?, ?)', (key, value, desc))
@@ -285,6 +289,8 @@ def init_db():
('app_description', '提供智能对话、多种智能体服务', '应用简介'),
('privacy_policy_url', '', '隐私政策链接'),
('user_agreement_url', '', '用户协议链接'),
('tts_provider', 'edge', 'TTS方案'),
('tts_voice', 'zh-CN-XiaoxiaoNeural', 'TTS语音'),
]
for key, value, desc in default_configs:
cursor.execute('SELECT COUNT(*) FROM system_configs WHERE key=?', (key,))
@@ -1386,12 +1392,62 @@ def get_frontend_config():
'description': system.get('app_description', '提供智能对话、多种智能体服务'),
'privacyPolicyUrl': system.get('privacy_policy_url', ''),
'userAgreementUrl': system.get('user_agreement_url', ''),
'ttsProvider': system.get('tts_provider', 'edge'),
'ttsVoice': system.get('tts_voice', 'zh-CN-XiaoxiaoNeural'),
}
}
return jsonify(config)
# ==================== TTS 语音合成 ====================
@app.route('/api/tts', methods=['POST'])
def generate_tts():
"""使用 Edge TTS 生成语音"""
data = request.json
text = data.get('text', '')
voice = data.get('voice', 'zh-CN-XiaoxiaoNeural') # 默认中文女声
if not text:
return jsonify({'error': '缺少文本内容'}), 400
try:
# 使用 asyncio 运行 edge_tts
async def generate_audio():
communicate = edge_tts.Communicate(text, voice)
audio_data = b''
for chunk in communicate.stream_sync():
if chunk['type'] == 'audio':
audio_data += chunk['data']
return audio_data
audio_data = asyncio.run(generate_audio())
# 返回音频数据MP3格式
return Response(audio_data, mimetype='audio/mpeg')
except Exception as e:
return jsonify({'error': f'TTS生成失败: {str(e)}'}), 500
@app.route('/api/tts/voices', methods=['GET'])
def get_tts_voices():
"""获取可用的 TTS 语音列表"""
try:
voices = asyncio.run(edge_tts.list_voices())
# 过滤中文语音
chinese_voices = [v for v in voices if v['Locale'].startswith('zh-')]
voice_list = [{
'name': v['ShortName'],
'gender': v['Gender'],
'locale': v['Locale']
} for v in chinese_voices]
return jsonify({'voices': voice_list})
except Exception as e:
return jsonify({'error': f'获取语音列表失败: {str(e)}'}), 500
# ==================== 启动 ====================
if __name__ == '__main__':