项目运行后打开浏览器http://127.0.0.1:9090/显示127.0.0.1 拒绝了我们的连接请求。 请试试以下办法: 检查网络连接 检查代理服务器和防火墙 ERR_CONNECTION_REFUSED是什么原因?如何处理?脚本如下:# /// script
requires-python = "==3.10.*"
dependencies = [
"flask",
"edge-tts",
"waitress"
]
///
import json,os
from pathlib import Path
import asyncio
from datetime import datetime
from io import BytesIO
import webbrowser
from threading import Timer
from flask import Flask, render_template, request, send_file, jsonify
from waitress import serve
import edge_tts
app = Flask(__name__,template_folder='.')
ROOT=Path(os.getcwd()).as_posix()
try:
with open(f'{ROOT}/edge_tts.json', 'r', encoding='utf-8') as f:
voices_data = json.load(f)except FileNotFoundError:
print("致命错误: 未找到 edge_tts.json。")
print("请确保 edge_tts.json 文件与 app.py 在同一目录下。")
voices_data = {}except json.JSONDecodeError:
print("致命错误: 无法解析 edge_tts.json。")
print("请确保它是一个有效的 JSON 文件。")
voices_data = {}
@app.route('/')
def index():
"""
渲染主 HTML 页面,并将语音数据传递给它。
'voices_data' 将在模板中被 JavaScript 使用。
"""
return render_template('index.html', voices_data=voices_data)
async def generate_audio(text, voice, rate, volume, pitch):
"""
一个异步函数,使用 edge-tts 库从文本生成音频,
并将其作为内存中的字节流返回。
"""
communicate = edge_tts.Communicate(text=text, voice=voice, rate=rate, volume=volume, pitch=pitch)
audio_buffer = BytesIO()
async for chunk in communicate.stream():
if chunk["type"] == "audio":
audio_buffer.write(chunk["data"])
audio_buffer.seek(0)
return audio_buffer
@app.route('/api/tts', methods=['POST'])
def tts_api():
"""
处理来自前端的 POST 请求,生成音频,
并将其作为 MP3 文件发送回去。
"""
data = request.get_json()
if not data:
return jsonify({"error": "无效的 JSON 请求"}), 400
text = data.get('text')
voice = data.get('voice')
rate = data.get('rate', '+0%')
volume = data.get('volume', '+0%')
pitch = data.get('pitch', '+0Hz')
if not text or not voice:
return jsonify({"error": "请求中缺少 'text' 或 'voice'"}), 400
try:
audio_buffer = asyncio.run(generate_audio(text, voice, rate, volume, pitch))
filename = datetime.now().strftime("%Y%m%d%H%M%S") + ".mp3"
return send_file(
audio_buffer,
mimetype='audio/mpeg',
as_attachment=True,
download_name=filename
)
except Exception as e:
print(f"TTS 生成过程中发生错误: {e}")
return jsonify({"error": "由于内部服务器错误,生成音频失败。"}), 500
def open_browser():
"""
在默认 Web 浏览器中打开应用。
"""
webbrowser.open_new("http://127.0.0.1:9090")
if name == '__main__':
HOST = '127.0.0.1'
PORT = 9090
print(f"服务器已启动,访问地址: http://{HOST}:{PORT}")
print("按 Ctrl+C 停止服务器")
Timer(1, open_browser).start()
serve(app, host='0.0.0.0', port=PORT)