Files
a2f-service/services/a2f_api/tts_service.py
2025-12-25 15:36:35 +08:00

36 lines
1.0 KiB
Python
Raw 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 threading
import pyttsx3
class TTSService:
_lock = threading.Lock()
def __init__(self, lang='zh-CN'):
self.lang = lang
def text_to_audio(self, text: str, output_path: str) -> str:
"""将文本转换为WAV音频文件使用pyttsx3"""
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with self._lock:
engine = pyttsx3.init()
try:
# 设置中文语音
voices = engine.getProperty('voices')
for voice in voices:
if 'chinese' in voice.name.lower() or 'zh' in voice.id.lower():
engine.setProperty('voice', voice.id)
break
# 设置语速
engine.setProperty('rate', 150)
# 保存为WAV
engine.save_to_file(text, output_path)
engine.runAndWait()
return output_path
finally:
engine.stop()
del engine