36 lines
1.0 KiB
Python
36 lines
1.0 KiB
Python
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
|