流式传输
This commit is contained in:
@ -1,20 +1,35 @@
|
||||
import os
|
||||
import threading
|
||||
import pyttsx3
|
||||
|
||||
class TTSService:
|
||||
_lock = threading.Lock()
|
||||
|
||||
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:
|
||||
"""将文本转换为WAV音频文件(使用pyttsx3)"""
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
self.engine.save_to_file(text, output_path)
|
||||
self.engine.runAndWait()
|
||||
return output_path
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user