70 lines
2.3 KiB
Python
70 lines
2.3 KiB
Python
"""本地 TTS 语音播报(IndexTTS2),仅 Windows 本地模式使用。
|
||
|
||
服务器/容器不会启用(无 torch、无声卡),由 fengxiang.tts.Speaker 在非 win32 平台直接跳过。
|
||
|
||
路径可通过环境变量覆盖,不再写死 E:\\:
|
||
FX_INDEXTTS_HOME IndexTTS2 工程目录
|
||
FX_INDEXTTS_VOICE 参考音色 wav 路径
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import sys
|
||
import tempfile
|
||
import time
|
||
|
||
_INDEXTTS_HOME = os.environ.get("FX_INDEXTTS_HOME", r"E:\2025Code\python\IndexTT\index-tts")
|
||
_INDEXTTS_MODEL_DIR = os.path.join(_INDEXTTS_HOME, "checkpoints")
|
||
_INDEXTTS_CFG = os.path.join(_INDEXTTS_MODEL_DIR, "config.yaml")
|
||
_DEFAULT_VOICE_PROMPT = os.environ.get(
|
||
"FX_INDEXTTS_VOICE", os.path.join(_INDEXTTS_HOME, "examples", "voice_01.wav")
|
||
)
|
||
|
||
_tts_instance = None
|
||
|
||
|
||
def _get_tts():
|
||
"""延迟初始化 IndexTTS2(首次加载模型 1-2 分钟)。"""
|
||
global _tts_instance
|
||
if _tts_instance is None:
|
||
if not os.path.isdir(_INDEXTTS_HOME):
|
||
raise FileNotFoundError(
|
||
f"未找到 IndexTTS2 目录: {_INDEXTTS_HOME}(可用 FX_INDEXTTS_HOME 指定)"
|
||
)
|
||
sys.path.insert(0, _INDEXTTS_HOME)
|
||
from indextts.infer_v2 import IndexTTS2
|
||
|
||
print("[TTS] 正在加载 IndexTTS2 模型(首次较慢)...")
|
||
_tts_instance = IndexTTS2(
|
||
cfg_path=_INDEXTTS_CFG,
|
||
model_dir=_INDEXTTS_MODEL_DIR,
|
||
use_fp16=True,
|
||
use_cuda_kernel=False,
|
||
use_deepspeed=False,
|
||
)
|
||
print("[TTS] 模型加载完成")
|
||
return _tts_instance
|
||
|
||
|
||
def speak(text: str, voice_prompt: str | None = None) -> str:
|
||
"""合成并播放,返回生成的 wav 路径。"""
|
||
if sys.platform != "win32":
|
||
raise RuntimeError("本地 TTS 仅支持 Windows(依赖 winsound)")
|
||
|
||
import winsound
|
||
|
||
voice_prompt = voice_prompt or _DEFAULT_VOICE_PROMPT
|
||
if not os.path.exists(voice_prompt):
|
||
raise FileNotFoundError(f"参考音色不存在: {voice_prompt}")
|
||
|
||
tts = _get_tts()
|
||
out = os.path.join(tempfile.gettempdir(), f"fx_tts_{int(time.time() * 1000)}.wav")
|
||
tts.infer(spk_audio_prompt=voice_prompt, text=text, output_path=out, verbose=False)
|
||
winsound.PlaySound(out, winsound.SND_FILENAME)
|
||
return out
|
||
|
||
|
||
if __name__ == "__main__":
|
||
speak("本地语音播报测试成功")
|