📦 第一阶段:环境准备与模型部署
1. 创建项目并安装核心依赖 打开你的终端,执行以下命令:
# 1. 创建项目目录
mkdir MyEmotionalTTS && cd MyEmotionalTTS
# 2. 创建 Python 虚拟环境(推荐)
python -m venv venv
# 在 Linux/Mac 上激活:source venv/bin/activate
# 在 Windows 上激活:venv\Scripts\activate
# 3. 安装 PyTorch (根据你的 CUDA 版本选择,以 CUDA 12.1 为例)
pip install torch torchaudio --index-url https://download.pytorch.org/whl/cu121
# 4. 安装 ChatTTS 及其他依赖
pip install ChatTTS transformers soundfile ipython
2. 下载并初始化 ChatTTS 模型
创建一个名为 init_model.py 的脚本,写入以下代码:
import ChatTTS
import torch
import warnings
warnings.filterwarnings("ignore")
# 初始化 ChatTTS
chat = ChatTTS.Chat()
# 加载模型(自动下载权重,约 2GB)
chat.load_models(compile=False)
# `compile=False` 可避免特定环境下的错误
# 查看可用模型参数(可选)
print("模型加载成功!")
print(f"设备:{chat.device}")
# 将模型设为推理模式(重要)
chat.eval()
# 保存模型对象以供后续使用(示例,实际我们会在封装类中管理)
# import pickle
# with open('chat_model.pkl', 'wb') as f:
# pickle.dump(chat, f)
运行它来下载和验证模型:
python init_model.py
🧱 第二阶段:核心封装与情感控制接口
创建一个核心封装类 EmotionalTTS.py,这是二次封装的精髓。
import ChatTTS
import torch
numpy np
soundfile sf
typing , ,
warnings
warnings.filterwarnings()
:
():
.chat = ChatTTS.Chat()
device:
.chat.load_models(=, device=device)
:
.chat.load_models(=)
.chat.()
.emotion_params_map = {
: {: , : },
: {: , : },
: {: , : },
: {: , : },
: {: , : }
}
()
() -> np.ndarray:
texts = [text]
params = .emotion_params_map.get(emotion, .emotion_params_map[])
rand_spk = np.random.randint(, ) speaker_embedding
torch.no_grad():
wavs, _ = .chat.infer(
texts,
params_refine_text={: },
params_infer_code={
: speaker_embedding,
: rand_spk,
: params[],
},
do_text_normalization=,
return_duration=
)
audio_data = wavs.squeeze()
speed != :
scipy signal
new_length = ((audio_data) / speed)
audio_data = signal.resample(audio_data, new_length)
save_path:
save_path.endswith():
save_path +=
sf.write(save_path, audio_data, samplerate=sample_rate)
()
audio_data, sample_rate
() -> []:
os
os.makedirs(save_dir, exist_ok=)
emotions :
emotions = [] * (texts)
file_paths = []
i, (text, emotion) ((texts, emotions)):
()
save_path = os.path.join(save_dir, )
.synthesize(text, emotion=emotion, save_path=save_path)
file_paths.append(save_path)
file_paths
() -> []:
(.emotion_params_map.keys())
() -> np.ndarray:
()
np.random.randn(, ).astype(np.float32)


