| | import asyncio |
| | import edge_tts |
| | from fastapi import FastAPI, Query, HTTPException |
| | from fastapi.responses import StreamingResponse |
| | import io |
| |
|
| | app = FastAPI() |
| |
|
| | |
| | |
| | |
| | |
| |
|
| | @app.get("/tts") |
| | async def tts_endpoint( |
| | text: str = Query(..., description="要转换的文字"), |
| | voice: str = Query("zh-CN-XiaoxiaoNeural", description="声音名称") |
| | ): |
| | try: |
| | |
| | communicate = edge_tts.Communicate(text, voice) |
| | |
| | |
| | audio_stream = io.BytesIO() |
| | async for chunk in communicate.stream(): |
| | if chunk["type"] == "audio": |
| | audio_stream.write(chunk["data"]) |
| | |
| | audio_stream.seek(0) |
| | |
| | |
| | return StreamingResponse(audio_stream, media_type="audio/mpeg") |
| | |
| | except Exception as e: |
| | raise HTTPException(status_code=500, detail=str(e)) |
| |
|
| | if __name__ == "__main__": |
| | import uvicorn |
| | uvicorn.run(app, host="0.0.0.0", port=7860) |