> 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/xtts-coqui.md).

# XTTS（Coqui）

使用 Coqui XTTS 进行带声音克隆的自然语音生成

使用 Coqui XTTS 通过声音克隆生成自然语音。

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

## 在 CLORE.AI 上租用

1. 访问 [CLORE.AI 市场](https://clore.ai/marketplace)
2. 按 GPU 类型、VRAM 和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价）
4. 配置你的订单：
   * 选择 Docker 镜像
   * 设置端口（SSH 用 TCP，Web UI 用 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问你的服务器

* 在以下位置查找连接信息 **我的订单**
* Web 界面：使用 HTTP 端口 URL
* SSH： `ssh -p <port> root@<proxy-address>`

## 什么是 XTTS？

XTTS（由 Coqui 提供）具有：

* 高质量文本转语音
* 仅需 6 秒音频即可进行声音克隆
* 支持 17 种语言
* 情感控制
* 支持流式传输

## 需求

| 模式   | 显存  | 推荐       |
| ---- | --- | -------- |
| 推理   | 4GB | RTX 3060 |
| 快速推理 | 6GB | RTX 3080 |
| 流式输出 | 4GB | RTX 3060 |

## 快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime
```

**端口：**

```
22/tcp
8000/http
```

**命令：**

```bash
pip install TTS && 
tts-server --model_name tts_models/multilingual/multi-dataset/xtts_v2
```

## 访问你的服务

部署后，找到你的 `http_pub` URL 在 **我的订单**:

1. 前往 **我的订单** 页面
2. 点击你的订单
3. 找到 `http_pub` URL（例如， `abc123.clorecloud.net`)

使用 `https://YOUR_HTTP_PUB_URL` 替代 `localhost` 在下面的示例中。

## 安装

```bash
pip install TTS
```

## 基础用法

### 简单 TTS

```python
from TTS.api import TTS

# 加载 XTTS v2
tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to("cuda")

# 生成语音
tts.tts_to_file(
    text="你好，这是 XTTS 文本转语音系统的测试。",
    file_path="output.wav",
    language="en"
)
```

### 声音克隆

```python
from TTS.api import TTS

tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to("cuda")

# 从参考音频克隆声音（6 秒以上）
tts.tts_to_file(
    text="这是我的克隆声音在说新文本。",
    file_path="cloned_output.wav",
    speaker_wav="reference_voice.wav",
    language="en"
)
```

## 多种语言

```python
from TTS.api import TTS

tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to("cuda")

# 英语
tts.tts_to_file(
    text="你好，今天过得怎么样？",
    file_path="english.wav",
    speaker_wav="voice.wav",
    language="en"
)

# 西班牙语
tts.tts_to_file(
    text="Hola, ¿cómo estás hoy?",
    file_path="spanish.wav",
    speaker_wav="voice.wav",
    language="es"
)

# 德语
tts.tts_to_file(
    text="Hallo, wie geht es dir heute?",
    file_path="german.wav",
    speaker_wav="voice.wav",
    language="de"
)

# 俄语
tts.tts_to_file(
    text="Привет, как дела?",
    file_path="russian.wav",
    speaker_wav="voice.wav",
    language="ru"
)
```

### 支持的语言

| 代码    | 语言   |
| ----- | ---- |
| en    | 英语   |
| es    | 西班牙语 |
| fr    | 法语   |
| de    | 德语   |
| it    | 意大利语 |
| pt    | 葡萄牙语 |
| pl    | 波兰语  |
| tr    | 土耳其语 |
| ru    | 俄语   |
| nl    | 荷兰语  |
| cs    | 捷克语  |
| ar    | 阿拉伯语 |
| zh-cn | 中文   |
| ja    | 日语   |
| hu    | 匈牙利语 |
| ko    | 韩语   |
| hi    | 印地语  |

## 流式 TTS

```python
from TTS.tts.configs.xtts_config import XttsConfig
from TTS.tts.models.xtts import Xtts
import torch
import sounddevice as sd

# 加载模型
config = XttsConfig()
config.load_json("path/to/config.json")
model = Xtts.init_from_config(config)
model.load_checkpoint(config, checkpoint_dir="path/to/model")
model.cuda()

# 获取说话人嵌入
gpt_cond_latent, speaker_embedding = model.get_conditioning_latents(
    audio_path="reference.wav"
)

# 流式生成
chunks = model.inference_stream(
    text="这是对 XTTS 系统的流式测试。",
    language="en",
    gpt_cond_latent=gpt_cond_latent,
    speaker_embedding=speaker_embedding,
    stream_chunk_size=20
)

# 实时播放
for chunk in chunks:
    audio = chunk.cpu().numpy()
    sd.play(audio, samplerate=24000)
    sd.wait()
```

## Gradio 界面

```python
import gradio as gr
from TTS.api import TTS
import tempfile

tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to("cuda")

def generate_speech(text, reference_audio, language):
    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
        if reference_audio:
            tts.tts_to_file(
                text=text,
                file_path=f.name,
                speaker_wav=reference_audio,
                language=language
            )
        else:
            tts.tts_to_file(
                text=text,
                file_path=f.name,
                language=language
            )
        return f.name

demo = gr.Interface(
    fn=generate_speech,
    inputs=[
        gr.Textbox(label="要朗读的文本", lines=5),
        gr.Audio(type="filepath", label="参考语音（可选）"),
        gr.Dropdown(
            ["en", "es", "fr", "de", "it", "pt", "ru", "zh-cn", "ja"],
            value="en",
            label="语言"
        )
    ],
    outputs=gr.Audio(label="生成的语音"),
    title="XTTS 声音克隆"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## API 服务器

```python
from fastapi import FastAPI, UploadFile, File, Form
from fastapi.responses import FileResponse
from TTS.api import TTS
import tempfile
import os

app = FastAPI()
tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to("cuda")

@app.post("/synthesize")
async def synthesize(
    text: str = Form(...),
    language: str = Form(default="en"),
    speaker: UploadFile = File(default=None)
):
    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as out_file:
        if speaker:
            # 保存上传的参考音频
            with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as ref_file:
                ref_file.write(await speaker.read())
                ref_path = ref_file.name

            tts.tts_to_file(
                text=text,
                file_path=out_file.name,
                speaker_wav=ref_path,
                language=language
            )
            os.unlink(ref_path)
        else:
            tts.tts_to_file(
                text=text,
                file_path=out_file.name,
                language=language
            )

        return FileResponse(out_file.name, media_type="audio/wav")

# 运行：uvicorn server:app --host 0.0.0.0 --port 8000
```

## 批量处理

```python
from TTS.api import TTS
import os

tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to("cuda")

texts = [
    "欢迎来到我们的平台。",
    "请查看以下信息。",
    "感谢您的关注。",
    "祝您今天愉快！"
]

reference_voice = "speaker.wav"
output_dir = "./audio_files"
os.makedirs(output_dir, exist_ok=True)

for i, text in enumerate(texts):
    output_path = f"{output_dir}/audio_{i:03d}.wav"

    tts.tts_to_file(
        text=text,
        file_path=output_path,
        speaker_wav=reference_voice,
        language="en"
    )

    print(f"已生成: {output_path}")
```

## 语音微调

为了获得更好的声音克隆效果：

```python
from TTS.tts.configs.xtts_config import XttsConfig
from TTS.tts.models.xtts import Xtts

config = XttsConfig()
model = Xtts.init_from_config(config)

# 使用多个参考样本以获得更好的质量
reference_files = [
    "sample1.wav",
    "sample2.wav",
    "sample3.wav"
]

# 从多个样本中提取说话人嵌入
gpt_cond_latent, speaker_embedding = model.get_conditioning_latents(
    audio_path=reference_files
)

# 使用平均嵌入生成
output = model.inference(
    text="高质量克隆语音。",
    language="en",
    gpt_cond_latent=gpt_cond_latent,
    speaker_embedding=speaker_embedding
)
```

## 音频预处理

```python
import librosa
import soundfile as sf

def prepare_reference(input_path, output_path, target_sr=22050):
    # 加载并重采样
    audio, sr = librosa.load(input_path, sr=target_sr)

    # 裁剪静音
    audio, _ = librosa.effects.trim(audio, top_db=20)

    # 归一化
    audio = librosa.util.normalize(audio)

    # 保存
    sf.write(output_path, audio, target_sr)

# 准备参考音频
prepare_reference("raw_voice.wav", "clean_voice.wav")
```

## 性能

| 模式   | GPU      | 速度        |
| ---- | -------- | --------- |
| 标准   | RTX 3060 | 约 0.5 倍实时 |
| 标准   | RTX 4090 | 约 2 倍实时   |
| 流式输出 | RTX 3060 | 约 1 倍实时   |
| 流式输出 | RTX 4090 | 约 3 倍实时   |

## 质量提示

* 使用 6-15 秒干净的参考音频
* 避免参考音频中的背景噪音
* 使文本与参考音频语言一致
* 使用多个参考样本以获得更好的结果

## 故障排查

### 声音质量差

* 干净的参考音频
* 更长的参考音频（10 秒以上）
* 匹配说话风格

### 语言发音错误

* 确保语言代码正确
* 使用母语者参考音频

### 生成缓慢

* 启用 GPU 推理
* 使用流式模式
* 减少每次调用的文本长度

## 成本估算

CLORE.AI 市场常见费率（截至 2024 年）：

| GPU       | 小时费率    | 日费率     | 4 小时会话  |
| --------- | ------- | ------- | ------- |
| RTX 3060  | \~$0.03 | \~$0.70 | \~$0.12 |
| RTX 3090  | \~$0.06 | \~$1.50 | \~$0.25 |
| RTX 4090  | \~$0.10 | \~$2.30 | \~$0.40 |
| A100 40GB | \~$0.17 | \~$4.00 | \~$0.70 |
| A100 80GB | \~$0.25 | \~$6.00 | \~$1.00 |

*价格因提供商和需求而异。请查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *以获取当前费率。*

**节省费用：**

* 使用 **竞价** 可中断工作市场——约三分之一的服务器将现货价格定得低于按需价格（中位数约优惠 13%），其余则与按需价格持平
* 使用 **CLORE** 代币支付
* 比较不同提供商的价格

## 下一步

* [Bark TTS](/guides/guides_v2-zh/yin-pin-yu-yu-yin/bark-tts.md) - 表现力 TTS
* [SadTalker](/guides/guides_v2-zh/talking-heads/sadtalker.md) - 口型说话头像
* [RVC 变声克隆](/guides/guides_v2-zh/yin-pin-yu-yu-yin/rvc-voice-clone.md) - 语音转换


---

# 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/xtts-coqui.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.
