Files
a2f-service/services/a2f_api/edge_tts_service.py
2025-12-26 11:29:31 +08:00

30 lines
988 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import asyncio
import edge_tts
class EdgeTTSService:
def __init__(self, lang='zh-CN'):
self.lang = lang
# 中文语音选项
self.voice_map = {
'zh-CN': 'zh-CN-XiaoxiaoNeural', # 晓晓
'zh-TW': 'zh-TW-HsiaoChenNeural',
'en-US': 'en-US-AriaNeural'
}
def text_to_audio(self, text: str, output_path: str) -> str:
"""将文本转换为WAV音频文件使用edge-tts"""
os.makedirs(os.path.dirname(output_path), exist_ok=True)
voice = self.voice_map.get(self.lang, 'zh-CN-XiaoxiaoNeural')
# edge-tts 是异步的,需要在同步函数中运行
asyncio.run(self._async_text_to_audio(text, output_path, voice))
return output_path
async def _async_text_to_audio(self, text: str, output_path: str, voice: str):
"""异步生成音频"""
communicate = edge_tts.Communicate(text, voice)
await communicate.save(output_path)