# RVC 声音克隆

使用基于检索的语音转换克隆并转换声音。

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

## 在 CLORE.AI 上租用

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

### 访问您的服务器

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

## 什么是 RVC？

RVC（基于检索的语音转换）可以：

* 通过少量训练克隆任意声音
* 转换歌唱/说话的声音
* 实时语音转换
* 高质量输出

## 要求

| 任务 | 最小显存 | 推荐       |
| -- | ---- | -------- |
| 推理 | 4GB  | RTX 3060 |
| 训练 | 8GB  | RTX 3090 |
| 实时 | 6GB  | RTX 3070 |

## 快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel
```

**端口：**

```
22/tcp
7865/http
```

**命令：**

```bash
apt-get update && apt-get install -y ffmpeg git && \
cd /workspace && \
git clone https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI.git && \
cd Retrieval-based-Voice-Conversion-WebUI && \
pip install -r requirements.txt && \
python infer-web.py --host 0.0.0.0 --port 7865
```

## 访问您的服务

部署完成后，查找您的 `http_pub` URL 在 **我的订单**:

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

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

## 安装

```bash

# 克隆仓库
git clone https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI.git
cd Retrieval-based-Voice-Conversion-WebUI

# 安装依赖
pip install -r requirements.txt

# 下载模型
python tools/download_models.py
```

## 语音转换（推理）

### 使用 Web UI

1. 打开 `http://<proxy>:7865`
2. 转到 “Model Inference” 选项卡
3. 上传音频文件
4. 选择语音模型
5. 调整设置
6. 点击 “Convert”

### Python API

```python
from infer_pack.models import SynthesizerTrnMs256NSFsid, SynthesizerTrnMs768NSFsid
from vc_infer_pipeline import VC
import torch
import soundfile as sf

# 加载模型
model_path = "./models/my_voice.pth"
index_path = "./models/my_voice.index"

vc = VC(
    model_path=model_path,
    config_path="./configs/v2/48k.json",
    device="cuda"
)

# 转换音频
audio, sr = sf.read("input.wav")
output = vc.convert(
    audio=audio,
    f0_method="rmvpe",  # 基频提取方法
    index_path=index_path,
    index_rate=0.75,
    f0_up_key=0,  # 音高调整（半音）
    protect=0.33
)

sf.write("output.wav", output, sr)
```

## 训练自定义语音

### 准备数据集

1. 收集 10-30 分钟的干净音频
2. 剪切为 5-15 秒的片段
3. 去除背景噪音/音乐

```bash

# 将音频拆分为片段
ffmpeg -i full_audio.mp3 -f segment -segment_time 10 -c copy clips/clip_%03d.mp3
```

### 通过 Web UI 训练

1. 转到 “Train” 选项卡
2. 输入实验名称
3. 设置训练文件夹路径
4. 点击 “Process data”
5. 点击 “Feature extraction”
6. 点击 “Train”

### 通过命令行训练

```bash

# 第 1 步：处理音频
python trainset_preprocess_pipeline_print.py \
    "./dataset" \
    48000 \
    8 \
    "./logs/experiment" \
    False

# 第 2 步：提取特征
python extract_f0_print.py \
    "./logs/experiment" \
    8 \
    "rmvpe"

python extract_feature_print.py \
    "cuda:0" \
    "1" \
    "0" \
    "0" \
    "./logs/experiment" \
    "v2"

# 第 3 步：训练
python train_nsf_sim_cache_sid_load_pretrain.py \
    -e "experiment" \
    -sr "48k" \
    -f0 1 \
    -bs 8 \
    -g 0 \
    -te 200 \
    -se 20 \
    -pg "./pretrained/f0G48k.pth" \
    -pd "./pretrained/f0D48k.pth" \
    -l 0 \
    -c 1 \
    -sw 0 \
    -v "v2"
```

## 训练参数

| 参数         | 说明     | 推荐      |
| ---------- | ------ | ------- |
| 采样率        | 音频质量   | 48000   |
| 批量大小       | 训练批次   | 8-16    |
| 轮数（Epochs） | 训练迭代次数 | 200-500 |
| 保存间隔       | 检查点频率  | 20-50   |
| f0 方法      | 基频提取   | rmvpe   |

## F0 方法

| 方法      | 质量 | 速度 | 适合场景 |
| ------- | -- | -- | ---- |
| pm      | 一般 | 快速 | 测试   |
| harvest | 良好 | 慢  | 通用   |
| crepe   | 很棒 | 中等 | 歌唱   |
| rmvpe   | 最佳 | 中等 | 全部   |

## 实时转换

### 设置

```python
import pyaudio
import numpy as np
from infer_pack.models import SynthesizerTrnMs256NSFsid
from vc_infer_pipeline import VC

# 初始化
vc = VC(model_path="./models/voice.pth", device="cuda")

# 音频设置
CHUNK = 1024
FORMAT = pyaudio.paFloat32
CHANNELS = 1
RATE = 48000

p = pyaudio.PyAudio()
stream_in = p.open(format=FORMAT, channels=CHANNELS, rate=RATE,
                   input=True, frames_per_buffer=CHUNK)
stream_out = p.open(format=FORMAT, channels=CHANNELS, rate=RATE,
                    output=True, frames_per_buffer=CHUNK)

# 实时循环
while True:
    audio_in = np.frombuffer(stream_in.read(CHUNK), dtype=np.float32)
    audio_out = vc.convert(audio_in)
    stream_out.write(audio_out.tobytes())
```

## 模型格式

### 转换为 ONNX

```python
import torch

# 加载 PyTorch 模型
model = torch.load("model.pth")

# 导出为 ONNX
torch.onnx.export(
    model,
    dummy_input,
    "model.onnx",
    input_names=["audio"],
    output_names=["converted"],
    dynamic_axes={"audio": {0: "length"}}
)
```

## 音频预处理

### 去噪

```python
import noisereduce as nr
import soundfile as sf

audio, sr = sf.read("noisy.wav")
reduced_noise = nr.reduce_noise(y=audio, sr=sr)
sf.write("clean.wav", reduced_noise, sr)
```

### 归一化音量

```python
from pydub import AudioSegment

audio = AudioSegment.from_wav("input.wav")
normalized = audio.normalize()
normalized.export("normalized.wav", format="wav")
```

### 去除静音

```python
from pydub import AudioSegment
from pydub.silence import split_on_silence

audio = AudioSegment.from_wav("input.wav")
chunks = split_on_silence(audio, min_silence_len=500, silence_thresh=-40)
combined = sum(chunks)
combined.export("no_silence.wav", format="wav")
```

## 批量处理

```python
import os
from vc_infer_pipeline import VC
import soundfile as sf

vc = VC(model_path="./models/voice.pth", device="cuda")

input_dir = "./inputs"
output_dir = "./outputs"
os.makedirs(output_dir, exist_ok=True)

for filename in os.listdir(input_dir):
    if filename.endswith(('.wav', '.mp3', '.flac')):
        input_path = os.path.join(input_dir, filename)
        output_path = os.path.join(output_dir, f"converted_{filename}")

        audio, sr = sf.read(input_path)
        converted = vc.convert(audio)
        sf.write(output_path, converted, sr)

        print(f"Converted: {filename}")
```

## 歌声转换

对于歌曲，请使用合适的设置：

```python
output = vc.convert(
    audio=audio,
    f0_method="rmvpe",  # 对歌唱最合适
    index_rate=0.5,     # 歌唱时使用较低值
    f0_up_key=-2,       # 调整音高以匹配
    protect=0.5         # 保护辅音
)
```

## 常见问题

### 声音听起来像机器人

* 使用更高质量的源音频
* 提高 protect 值（0.4-0.5）
* 尝试不同的 f0 方法

### 音高问题

* 调整 f0\_up\_key
* 使用 rmvpe f0 方法
* 确保训练数据中音高一致

### 音频质量

* 使用 48kHz 采样率
* 从训练数据中移除背景噪音
* 增加训练轮数

## API 服务器

```python
from fastapi import FastAPI, UploadFile
from fastapi.responses import FileResponse
from vc_infer_pipeline import VC
import soundfile as sf
import tempfile

app = FastAPI()
vc = VC(model_path="./models/voice.pth", device="cuda")

@app.post("/convert")
async def convert_voice(file: UploadFile, pitch: int = 0):
    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_in:
        content = await file.read()
        tmp_in.write(content)
        tmp_in_path = tmp_in.name

    audio, sr = sf.read(tmp_in_path)
    converted = vc.convert(audio, f0_up_key=pitch)

    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_out:
        sf.write(tmp_out.name, converted, sr)
        return FileResponse(tmp_out.name, media_type="audio/wav")
```

## 训练提示

### 为获得更好质量

* 使用 20 分钟以上的干净音频
* 去除所有背景噪音
* 保持麦克风/录音设备设置一致
* 包含多样的表情/情感

### 为更快训练

* 使用 8-16 的批量大小
* 启用混合精度
* 为数据集使用 NVMe SSD

## 性能

| 任务           | GPU      | 时间       |
| ------------ | -------- | -------- |
| 推理（1 分钟音频）   | RTX 3090 | \~5s     |
| 训练（30 分钟数据集） | RTX 3090 | \~2 小时   |
| 实时转换         | RTX 3070 | <50ms 延迟 |

## 故障排除

## 费用估算

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) *以获取当前费率。*

**节省费用：**

* 使用 **竞价（Spot）** 为弹性工作负载使用市场（通常便宜 30-50%）
* 使用以下方式支付 **CLORE** 代币
* 比较不同提供商的价格

## 下一步

* [Bark TTS](/guides/guides_v2-zh/yin-pin-yu-yu-yin/bark-tts.md) - 文本到语音
* [AudioCraft Music](/guides/guides_v2-zh/yin-pin-yu-yu-yin/audiocraft-music.md) - 音乐生成
* [Whisper 转录](/guides/guides_v2-zh/yin-pin-yu-yu-yin/whisper-transcription.md) - 语音转文本


---

# Agent Instructions: 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:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yin-pin-yu-yu-yin/rvc-voice-clone.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
