21 lines
673 B
Python
21 lines
673 B
Python
import os
|
|
import pyttsx3
|
|
|
|
class TTSService:
|
|
def __init__(self, lang='zh-CN'):
|
|
self.lang = lang
|
|
self.engine = pyttsx3.init()
|
|
|
|
if lang == 'zh-CN':
|
|
voices = self.engine.getProperty('voices')
|
|
for voice in voices:
|
|
if 'chinese' in voice.name.lower() or 'zh' in voice.id.lower():
|
|
self.engine.setProperty('voice', voice.id)
|
|
break
|
|
|
|
def text_to_audio(self, text: str, output_path: str) -> str:
|
|
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
self.engine.save_to_file(text, output_path)
|
|
self.engine.runAndWait()
|
|
return output_path
|