流式传输

This commit is contained in:
yinsx
2025-12-25 15:36:35 +08:00
parent e56f47076c
commit 14bfdcbf51
19 changed files with 1191 additions and 65 deletions

View File

@ -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