| 1 | import os |
| 2 | from typing import Optional |
| 3 | |
| 4 | |
| 5 | def speed_to_rate(speed: Optional[float]) -> str: |
| 6 | value = 1.0 if speed is None else float(speed) |
| 7 | percent = int(round((value - 1.0) * 100)) |
| 8 | sign = "+" if percent >= 0 else "" |
| 9 | return f"{sign}{percent}%" |
| 10 | |
| 11 | |
| 12 | async def generate_edge_tts( |
| 13 | text: str, |
| 14 | output_path: str, |
| 15 | voice: str = "zh-CN-YunjianNeural", |
| 16 | speed: float = 1.0, |
| 17 | ) -> str: |
| 18 | try: |
| 19 | import edge_tts |
| 20 | except ImportError as exc: |
| 21 | raise RuntimeError("edge-tts is required for audio generation. Install backend dependencies again.") from exc |
| 22 | |
| 23 | os.makedirs(os.path.dirname(output_path), exist_ok=True) |
| 24 | communicate = edge_tts.Communicate(text=text, voice=voice, rate=speed_to_rate(speed)) |
| 25 | await communicate.save(output_path) |
| 26 | return output_path |
| 27 |