1. 环境拓扑与依赖配置 系统要求:macOS 14.0+, Python 3.10, Apple Silicon 芯片。
# 1. 创建 Python 3.10 隔离环境 conda create -n chattts python=3.10 -y conda activate chattts # 2. 安装核心计算与音频处理库 pip install torch torchaudio requests huggingface_hub # 3. 从源代码安装 ChatTTS 引擎 pip install git+https://github.com/2noise/ChatTTS.git 2. 权重获取与离线化处理(绕过 DNS 限制) 针对部分网络环境(如校园网)对 HuggingFace 节点的限制,采用镜像站手动同步模式。
# 设置镜像端点并下载 1.1GB 模型权重 export HF_ENDPOINT=https://hf-mirror.com python -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='2Noise/ChatTTS', local_dir='./asset', local_dir_use_symlinks=False, endpoint='https://hf-mirror.com')" 3. 核心生产脚本:read_blog.py 该脚本集成了设备自动检测(MPS 加速)、文本预处理以及分段推理逻辑。
import ChatTTS import torch import torchaudio import re import os def run(): # 设备检测:启用 Apple 硬件加速 device = torch.device('mps') if torch.backends.mps.is_available() else torch.device('cpu') chat = ChatTTS.Chat() # 加载本地模型路径 chat.load(source='local', custom_path='./asset', device=device) # 文档读取与纯净化 target_file = "blog.md" if not os.path.exists(target_file): print(f"File not found: {target_file}"); return with open(target_file, 'r', encoding='utf-8') as f: text = f.read() # 移除 Markdown 结构字符与公式符号 text = text.replace('$', '').replace('#', '').strip() paragraphs = [p.strip() for p in text.split('\n\n') if len(p.strip()) > 5] # 提取音色特征 spk_emb = chat.sample_random_speaker() all_wavs = [] for i, p in enumerate(paragraphs): # 推理合成并注入口语化停顿 wavs = chat.infer([f"{p} [uv_break]"], params_infer={'spk_emb': spk_emb}) all_wavs.append(torch.from_numpy(wavs[0])) # 音频合并与持久化存储 res = torch.cat(all_wavs, dim=-1) torchaudio.save("walk_listen.wav", res, 24000) if __name__ == "__main__": run() 4. 运行逻辑与数据流图 系统运行分为四个阶段: