> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/yin-pin-yu-yu-yin/melotts.md).

# MeloTTS

在 Clore.ai GPU 上运行高质量、多语言、快速推理的 MeloTTS

MeloTTS 是一个高质量的多语言文本转语音库，由 **MyShell AI**. 它提供快速、自然的语音合成，支持多种语言和英语口音，专为研究和生产部署而设计。MeloTTS 针对速度进行了优化——即使在 CPU 上也能显著快于实时生成语音——同时保持适合商业使用的高音频质量。

MeloTTS 当前支持：

* **英语** (美式、英式、印度式、澳式、默认)
* **中文（简体及中英混合）**
* **日语**
* **韩语**
* **西班牙语**
* **法语**

主要亮点：

* ⚡ **快速推理** —— 在 CPU 上快于实时，在 GPU 上飞快
* 🌍 **多语言** —— 6 种语言，英语带口音变体
* 🐳 **可直接用于 Docker** —— 提供官方 Docker 镜像
* 🔌 **REST API** —— 可通过 HTTP API 集成到任何应用中
* 📱 **适合生产环境** —— 用于 MyShell 的消费级产品

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

***

## 服务器要求

| 参数     | 最低                    | 推荐                     |
| ------ | --------------------- | ---------------------- |
| GPU    | NVIDIA GTX 1080（8 GB） | NVIDIA RTX 3090（24 GB） |
| 显存     | 4 GB                  | 8–16 GB                |
| 内存     | 8 GB                  | 16 GB                  |
| CPU    | 4 核                   | 8 核                    |
| 磁盘     | 10 GB                 | 20 GB                  |
| 操作系统   | Ubuntu 20.04+         | Ubuntu 22.04           |
| CUDA   | 11.7+（可选）             | 12.1+                  |
| Python | 3.8+                  | 3.10                   |
| 端口     | 22, 8888              | 22, 8888               |

{% hint style="info" %}
MeloTTS 的效率非常高——它在 CPU 上也能很好地运行，适合单次请求，而 GPU 则能大幅提升批量处理能力。即使是入门级 GPU，也能显著提升吞吐量。
{% endhint %}

***

## 在 CLORE.AI 上快速部署

{% hint style="warning" %}
**注意：** MeloTTS 在 Docker Hub 上没有官方预构建的 Docker 镜像（`myshell-ai/melotts` 并不存在）。推荐的做法是使用 NVIDIA CUDA 基础镜像，并通过官方 GitHub 仓库中的 pip 安装 MeloTTS。
{% endhint %}

### 1. 找到合适的服务器

前往 [CLORE.AI 市场](https://clore.ai/marketplace) 并按以下条件筛选：

* **显存**：≥ 4 GB（低负载时可仅用 CPU）
* **GPU**：任意 NVIDIA GPU（GTX 1080 及以上、RTX 系列、A100）
* **磁盘**：≥ 10 GB

### 2. 配置你的部署

**Docker 镜像：**

```
nvidia/cuda:12.8.1-devel-ubuntu22.04
```

**端口映射：**

```
22 → SSH 访问
8888 → MeloTTS API 服务器
```

**环境变量：**

```
NVIDIA_VISIBLE_DEVICES=all
```

**启动命令** （在通过 SSH 登录服务器后运行）：

```bash
apt-get update && apt-get install -y python3-pip ffmpeg espeak-ng git && \\
git clone https://github.com/myshell-ai/MeloTTS.git && \\
cd MeloTTS && pip install -e . && \\
python -m unidic download && \\
python3 -c "import nltk; nltk.download('averaged_perceptron_tagger_eng')" && \\
python -m melo.api_server --host 0.0.0.0 --port 8888
```

### 3. 访问 API

```
http://<your-clore-server-ip>:8888
```

测试命令：

```bash
curl -X POST http://<server-ip>:8888/synthesize \\
  -H "Content-Type: application/json" \\
  -d '{"text": "来自 Clore.ai 的问候！", "language": "EN", "speaker_id": "EN-Default"}'
```

***

## 逐步设置

### 步骤 1：通过 SSH 登录你的服务器

```bash
ssh root@<your-clore-server-ip> -p <ssh-port>
```

### 步骤 2：构建并运行容器

由于 MeloTTS 没有预构建的 Docker Hub 镜像，请使用 NVIDIA CUDA 基础镜像并从源码安装 MeloTTS：

```bash
# 运行一个 CUDA 容器并在其中安装 MeloTTS
docker run -d \\
  --name melotts \\
  --gpus all \\
  -p 8888:8888 \\
  -v /workspace/melotts/outputs:/app/outputs \\
  -e NVIDIA_VISIBLE_DEVICES=all \\
  nvidia/cuda:12.8.1-devel-ubuntu22.04 \\
  bash -c "apt-get update && apt-get install -y python3-pip ffmpeg espeak-ng git && \\
    git clone https://github.com/myshell-ai/MeloTTS.git /app/MeloTTS && \\
    cd /app/MeloTTS && pip install -e . && \\
    python -m unidic download && \\
    python3 -c \"import nltk; nltk.download('averaged_perceptron_tagger_eng')\" && \\
    python -m melo.api_server --host 0.0.0.0 --port 8888"
```

或者，从源码构建自定义 Docker 镜像：

```bash
git clone https://github.com/myshell-ai/MeloTTS.git
cd MeloTTS
docker build -t melotts:local .
docker run -d \\
  --name melotts \\
  --gpus all \\
  -p 8888:8888 \\
  melotts:local
```

### 步骤 3：验证服务是否正在运行

```bash
# 查看容器日志
docker logs -f melotts

# 等待启动，然后测试
curl http://localhost:8888/health
```

### 步骤 4：替代方案 — Jupyter Notebook 界面

```bash
docker run -d \\
  --name melotts-jupyter \\
  --gpus all \\
  -p 8888:8888 \\
  nvidia/cuda:12.8.1-devel-ubuntu22.04 \\
  bash -c "pip install jupyter melo-tts && \\
    jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root"
```

访问地址： `http://<server-ip>:8888`

### 步骤 5：使用 pip 安装（不使用 Docker）

```bash
# 安装系统依赖
apt-get install -y python3-pip ffmpeg espeak-ng

# 安装 MeloTTS
pip install melo-tts

# 下载所需的 NLTK 数据
python3 -c "import nltk; nltk.download('averaged_perceptron_tagger_eng')"
```

***

## 使用示例

### 示例 1：基础英语 TTS（Python）

```python
from melo.api import TTS

# 初始化英语 TTS
speed = 1.0  # 调整语速（0.5 = 慢，2.0 = 快）
device = 'cuda'  # 如果没有 GPU，可使用 'cpu'

tts = TTS(language='EN', device=device)

# 获取可用的 speaker ID
speakers = tts.hps.data.spk2id
print("可用说话人：", list(speakers.keys()))
# 输出：['EN-Default', 'EN-US', 'EN-GB', 'EN-India', 'EN-Australia', 'EN-Brazil']

# 生成语音
speaker_ids = tts.hps.data.spk2id
output_path = "output_english.wav"

tts.tts_to_file(
    text="欢迎使用 Clore.ai，您的 AI 工作负载 GPU 云市场。几分钟内即可租用强大的 GPU。",
    speaker_id=speaker_ids['EN-Default'],
    output_path=output_path,
    speed=speed
)

print(f"已保存到：{output_path}")
```

***

### 示例 2：多语言 TTS

```python
from melo.api import TTS

device = 'cuda'

# 定义语言-文本对
language_texts = [
    ('EN', 'EN-US', "GPU 计算已经改变了人工智能研究和开发。"),
    ('EN', 'EN-GB', "英国在 AI 投资和创新方面领先欧洲。"),
    ('ZH', 'ZH', "Clore.ai是一个去中心化的GPU云计算市场，为AI开发者提供算力服务。"),
    ('JP', 'JP', "人工知能の発展には大規模な計算資源が必要です。"),
    ('KR', 'KR', "Clore.ai는 AI 연구자를 위한 GPU 클라우드 마켓플레이스입니다."),
    ('SP', 'SP', "La inteligencia artificial está transformando todas las industrias del mundo."),
    ('FR', 'FR', "L'intelligence artificielle révolutionne la façon dont nous travaillons et vivons."),
]

for lang, speaker, text in language_texts:
    try:
        tts = TTS(language=lang, device=device)
        speaker_id = tts.hps.data.spk2id[speaker]

        output_file = f"output_{lang}_{speaker}.wav"
        tts.tts_to_file(text=text, speaker_id=speaker_id, output_path=output_file)
        print(f"✓ 已生成 [{lang}]: {output_file}")
    except Exception as e:
        print(f"✗ 错误 [{lang}]: {e}")
```

***

### 示例 3：REST API 使用

```python
import requests
import json

API_BASE = "http://<your-clore-server-ip>:8888"

# 检查可用语音
response = requests.get(f"{API_BASE}/voices")
print("可用语音：", json.dumps(response.json(), indent=2))

# 合成语音
def synthesize(text, language="EN", speaker="EN-Default", speed=1.0):
    payload = {
        "text": text,
        "language": language,
        "speaker_id": speaker,
        "speed": speed,
        "format": "wav"
    }

    response = requests.post(
        f"{API_BASE}/synthesize",
        json=payload,
        timeout=30
    )

    if response.status_code == 200:
        return response.content
    else:
        raise Exception(f"API 错误：{response.status_code} - {response.text}")

# 生成样本
samples = [
    ("你好，我是在 Clore.ai GPU 服务器上运行的 MeloTTS。", "EN", "EN-US"),
    ("这是英式英语口音变体。", "EN", "EN-GB"),
    ("让我演示印度英语口音。", "EN", "EN-India"),
]

for text, lang, speaker in samples:
    audio_bytes = synthesize(text, lang, speaker)
    filename = f"api_output_{speaker.replace('-', '_')}.wav"
    with open(filename, "wb") as f:
        f.write(audio_bytes)
    print(f"已保存：{filename}")
```

***

### 示例 4：高速批量处理

```python
from melo.api import TTS
from concurrent.futures import ThreadPoolExecutor
import soundfile as sf
import time
import numpy as np
from pathlib import Path

device = 'cuda'
tts = TTS(language='EN', device=device)
speaker_id = tts.hps.data.spk2id['EN-US']

# 大批量文本
texts = [
    f"这是第 {i} 句。它演示了在 Clore.ai GPU 基础设施上使用 MeloTTS 进行快速批量处理。"
    for i in range(1, 51)  # 50 句
]

output_dir = Path("batch_output")
output_dir.mkdir(exist_ok=True)

start_time = time.time()

# 批量处理
for i, text in enumerate(texts):
    output_path = str(output_dir / f"batch_{i+1:03d}.wav")
    tts.tts_to_file(
        text=text,
        speaker_id=speaker_id,
        output_path=output_path,
        speed=1.0,
        quiet=True
    )
    if (i + 1) % 10 == 0:
        elapsed = time.time() - start_time
        print(f"进度：{i+1}/50 | 用时：{elapsed:.1f}s | 速率：{(i+1)/elapsed:.1f} 句/秒")

total_time = time.time() - start_time
print(f"\n批处理完成：{len(texts)} 句，耗时 {total_time:.1f}s")
print(f"平均：每句 {total_time/len(texts)*1000:.0f}ms")
```

***

### 示例 5：中英混合 TTS

```python
from melo.api import TTS

device = 'cuda'
tts = TTS(language='ZH', device=device)
speaker_id = tts.hps.data.spk2id['ZH']

# 中英混合文本（中文 + 英文）
mixed_texts = [
    "我们使用Clore.ai的GPU服务器来运行machine learning workloads。",
    "今天的AI conference讨论了large language models和speech synthesis技术。",
    "我的startup需要GPU资源来训练我们的deep learning模型。",
    "Clore.ai提供了非常competitive的价格，比AWS和GCP便宜很多。",
]

for i, text in enumerate(mixed_texts):
    output_file = f"mixed_zh_en_{i+1}.wav"
    tts.tts_to_file(
        text=text,
        speaker_id=speaker_id,
        output_path=output_file,
        speed=0.9  # 语速稍慢以便更清晰
    )
    print(f"已生成：{output_file}")
    print(f"  文本：{text[:60]}...")
```

***

## 配置

### Docker Compose 设置

由于 MeloTTS 没有官方 Docker Hub 镜像，请使用 NVIDIA CUDA 基础镜像并在启动时从源码安装 MeloTTS：

```yaml
version: '3.8'

services:
  melotts:
    image: nvidia/cuda:12.8.1-devel-ubuntu22.04
    container_name: melotts
    runtime: nvidia
    environment:
      - NVIDIA_VISIBLE_DEVICES=all
      - PYTHONDONTWRITEBYTECODE=1
    ports:
      - "8888:8888"
    volumes:
      - ./outputs:/app/outputs
      - ./cache:/root/.cache
    command: >
      bash -c "apt-get update && apt-get install -y python3-pip ffmpeg espeak-ng git &&
      git clone https://github.com/myshell-ai/MeloTTS.git /app/MeloTTS &&
      cd /app/MeloTTS && pip install -e . &&
      python -m unidic download &&
      python3 -c 'import nltk; nltk.download(\"averaged_perceptron_tagger_eng\")' &&
      python -m melo.api_server --host 0.0.0.0 --port 8888"
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8888/health"]
      interval: 30s
      timeout: 10s
      retries: 3
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              数量：1
              capabilities: [gpu]
```

### API 配置选项

| 参数          | 默认值         | 描述                      |
| ----------- | ----------- | ----------------------- |
| `--host`    | `127.0.0.1` | 绑定地址（使用 `0.0.0.0` 用于公网） |
| `--port`    | `8888`      | API 服务器端口               |
| `--workers` | `1`         | 工作进程数量                  |
| `--device`  | `自动`        | `cuda`, `cpu`，或 `自动`    |

### 支持的语言和说话人

| 语言   | 代码   | 说话人 ID                                                                  |
| ---- | ---- | ----------------------------------------------------------------------- |
| 英语   | `EN` | `EN-Default`, `EN-US`, `EN-GB`, `EN-India`, `EN-Australia`, `EN-Brazil` |
| 中文   | `ZH` | `ZH`                                                                    |
| 日语   | `JP` | `JP`                                                                    |
| 韩语   | `KR` | `KR`                                                                    |
| 西班牙语 | `SP` | `SP`                                                                    |
| 法语   | `FR` | `FR`                                                                    |

***

## 性能提示

### 1. GPU 与 CPU 基准测试

MeloTTS 性能（RTF = 实时因子，越低越好）：

| 设备       | RTF     | 备注         |
| -------- | ------- | ---------- |
| CPU（8 核） | \~0.3x  | 速度快，适合低负载  |
| RTX 3080 | \~0.05x | 比实时快 20 倍  |
| RTX 4090 | \~0.02x | 比实时快 50 倍  |
| A100     | \~0.01x | 比实时快 100 倍 |

### 2. 针对吞吐量优化

```python
# 禁用推理时的梯度计算
import torch

with torch.no_grad():
    tts.tts_to_file(text, speaker_id, output_path)
```

### 3. 预热模型

```python
# 运行一次预热推理以加载 CUDA 内核
tts.tts_to_file(
    text="warmup",
    speaker_id=speaker_id,
    output_path="/dev/null"
)
print("模型已预热，已准备好进行快速推理")
```

### 4. 调整音频质量与速度

```python
# 更快（音质略低）
tts.tts_to_file(text, speaker_id, output_path, speed=1.2)

# 更慢的语音（发音更清晰）
tts.tts_to_file(text, speaker_id, output_path, speed=0.8)
```

### 5. 内存效率

```python
# 在大批量之间释放 GPU 内存
import gc
import torch

gc.collect()
torch.cuda.empty_cache()
```

***

## 故障排查

### 问题： `espeak-ng` 未找到

```bash
apt-get install -y espeak-ng
python3 -c "import phonemizer; print('phonemizer OK')"
```

### 问题：缺少 NLTK 数据

```bash
python3 -c "
import nltk
nltk.download('averaged_perceptron_tagger_eng')
nltk.download('punkt')
"
```

### 问题：8888 端口与 Jupyter 冲突

MeloTTS 默认使用 8888 端口，这与 Jupyter Notebook 冲突。解决方案：

```bash
# 方案 1：让 MeloTTS 运行在不同端口
python -m melo.api_server --host 0.0.0.0 --port 8889

# 方案 2：让 Jupyter 运行在不同端口
jupyter notebook --port 8890
```

### 问题：中文文本显示不正确

```bash
# 安装中文语言支持
pip install jieba
apt-get install -y python3-opencc

# 测试
python3 -c "from melo.api import TTS; t = TTS('ZH'); print('ZH OK')"
```

### 问题：Docker 镜像拉取失败

```bash
# 改为从源码构建
git clone https://github.com/myshell-ai/MeloTTS.git
cd MeloTTS
pip install -e .
python3 -c "import nltk; nltk.download('averaged_perceptron_tagger_eng')"
```

### 问题：GPU 上推理缓慢

```bash
# 检查是否正在使用 GPU
python3 -c "
import torch
from melo.api import TTS
tts = TTS('EN', device='cuda')
print(f'Device: {next(tts.model.parameters()).device}')
print(f'CUDA available: {torch.cuda.is_available()}')
"
```

***

## Clore.ai GPU 推荐

MeloTTS 体积轻量——它在低负载下可在 CPU 上良好运行，并随 GPU 算力线性扩展。你不需要昂贵的硬件。

| GPU       | 显存    | Clore.ai 价格                       | RTF（实时因子）         | 容量          |
| --------- | ----- | --------------------------------- | ----------------- | ----------- |
| 仅 CPU     | —     | 约 $0.02/小时                        | 约 0.3×            | 约 3 请求/分钟   |
| RTX 3090  | 24 GB | $0.07–0.21/小时                     | 约 0.02×（50 倍实时）   | 约 100 请求/分钟 |
| RTX 4090  | 24 GB | $0.14–0.42/小时                     | 约 0.01×（100 倍实时）  | 约 200 请求/分钟 |
| A100 40GB | 40 GB | [裸机](https://clore.ai/bare-metal) | 约 0.005×（200 倍实时） | 约 400 请求/分钟 |

{% hint style="info" %}
**TTS 工作负载的最佳性价比：** 售价 $0.07–0.21/小时的 RTX 3090 可提供 50 倍实时的 TTS 速度。对于服务数百名用户的生产 API 来说，这已经绰绰有余。仅 CPU 实例（$0.07–0.21/小时）则非常适合开发和低流量部署。
{% endhint %}

**生产环境推荐：** 对于一个服务 10–50 个并发用户的多语言 TTS API，RTX 3090 是最理想的选择。建议通过横向扩展（多实例）而不是升级到昂贵的 A100——MeloTTS 并不会随着更高端 GPU 的提升而成比例受益。

***

## 链接

* **GitHub**: <https://github.com/myshell-ai/MeloTTS>
* **Docker**：没有官方 Docker Hub 镜像——请从 [GitHub 源码](https://github.com/myshell-ai/MeloTTS) 使用 `nvidia/cuda:12.8.1-devel-ubuntu22.04` 基础镜像
* **论文**: <https://arxiv.org/abs/2406.06753>
* **Hugging Face**: <https://huggingface.co/myshell-ai/MeloTTS-English>
* **MyShell AI**: <https://myshell.ai>
* **CLORE.AI 市场**: <https://clore.ai/marketplace>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yin-pin-yu-yu-yin/melotts.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
