fix: 修复ChatTTS音频代理路由和音频播放错误处理
This commit is contained in:
29
main.py
29
main.py
@@ -4,9 +4,10 @@
|
||||
|
||||
import os
|
||||
import uvicorn
|
||||
import aiohttp
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
# 导入后端服务
|
||||
@@ -24,6 +25,32 @@ app.add_middleware(
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
# ChatTTS 音频代理(解决 HTTPS 页面访问 HTTP 资源问题)
|
||||
@app.get("/chattts/audio/{filename}")
|
||||
async def proxy_chattts_audio(filename: str):
|
||||
"""代理 ChatTTS 音频文件"""
|
||||
chattts_url = os.getenv("CHATTTS_URL", "http://192.168.2.5:12002")
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(
|
||||
f"{chattts_url}/audio/{filename}",
|
||||
timeout=aiohttp.ClientTimeout(total=30)
|
||||
) as resp:
|
||||
if resp.status != 200:
|
||||
return Response(content=b'{"detail":"Audio not found"}', status_code=404, media_type="application/json")
|
||||
|
||||
audio_data = await resp.read()
|
||||
return Response(
|
||||
content=audio_data,
|
||||
media_type="audio/wav",
|
||||
headers={"Cache-Control": "public, max-age=3600"}
|
||||
)
|
||||
except Exception as e:
|
||||
return Response(content=f'{"detail":"{str(e)}"}'.encode(), status_code=500, media_type="application/json")
|
||||
|
||||
|
||||
# 挂载 API
|
||||
app.mount("/api", api_app)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user