# Kokoro TTS

Kokoro 是一个拥有 8200 万参数的文本到语音模型，性能远超其体量。尽管体积很小（显存低于 2 GB），它能够生成非常自然的英语语音，并且即使在低配硬件上也能实现实时或更快的速度。Kokoro 使用 Apache 2.0 许可，内置多种语音风格，支持 CPU 推理，适合实时应用、聊天机器人和边缘部署。

**HuggingFace：** [hexgrad/Kokoro-82M](https://huggingface.co/hexgrad/Kokoro-82M) **PyPI：** [kokoro](https://pypi.org/project/kokoro/) **许可：** Apache 2.0

## 主要特性

* **82M 参数** — 可用的高质量 TTS 模型中体积最小的之一
* **< 2 GB 显存** — 几乎可以在任何 GPU 上运行，甚至可以在 CPU 上运行
* **多种语音风格** — 美式英语、英式英语；男性和女性声音
* **实时或更快** — 低延迟推理，适合流式处理
* **流式生成** — 随着音频产生即可输出音频块
* **多语言支持** — 英语（主要），日语（`misaki[ja]`），中文（`misaki[zh]`)
* **Apache 2.0** — 个人和商业用途免费

## 要求

| 组件     | 最低             | 推荐    |
| ------ | -------------- | ----- |
| GPU    | 任何带 2 GB 显存的设备 | 按小时费率 |
| 显存     | 2 GB           | 4 GB  |
| 内存     | 4 GB           | 8 GB  |
| 磁盘     | 500 MB         | 1 GB  |
| Python | 3.9+           | 3.11  |
| 系统     | 已安装 espeak-ng  | —     |

**Clore.ai 建议：** 一块 RTX 3060（\~$0.15–0.30/天）绰绰有余。Kokoro 甚至可以在仅有 CPU 的实例上运行，提供极具成本效益的 TTS。

## 安装

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

# 安装 Kokoro 和音频 I/O
pip install kokoro>=0.9.4 soundfile torch

# 支持日语（可选）
pip install misaki[ja]

# 支持中文（可选）
pip install misaki[zh]

# 验证
python -c "from kokoro import KPipeline; print('Kokoro ready')"
```

## 快速开始

```python
from kokoro import KPipeline
import soundfile as sf

# 初始化流水线
# 'a' = 美式英语，'b' = 英式英语
pipeline = KPipeline(lang_code='a')

text = """
Kokoro 是一个轻量级的文本到语音模型，只有八千二百万
参数。尽管体积小，但它能产生自然且富有表现力的语音。
"""

# 生成音频 — 语音选项： af_heart、af_bella、af_nicole、af_sarah、af_sky、
#                                  am_adam、am_michael、bf_emma、bf_isabella、bm_george、bm_lewis
generator = pipeline(text, voice='af_heart', speed=1.0)

for i, (graphemes, phonemes, audio) in enumerate(generator):
    sf.write(f'output_{i}.wav', audio, 24000)
    print(f"Chunk {i}: {graphemes[:50]}...")

print("完成！")
```

## 使用示例

### 多语音对比

用不同的声音生成相同文本进行比较：

```python
from kokoro import KPipeline
import soundfile as sf

pipeline = KPipeline(lang_code='a')

text = "Welcome to Clore.ai, the peer-to-peer GPU marketplace."

voices = ['af_heart', 'af_bella', 'am_adam', 'am_michael']

for voice in voices:
    generator = pipeline(text, voice=voice, speed=1.0)
    for i, (gs, ps, audio) in enumerate(generator):
        sf.write(f'{voice}_{i}.wav', audio, 24000)
    print(f"Generated: {voice}")
```

### 带速度控制的英式英语

```python
from kokoro import KPipeline
import soundfile as sf

# 'b' = 英式英语
pipeline = KPipeline(lang_code='b')

text = "Good afternoon. This is a demonstration of British English synthesis."

# speed < 1.0 = 更慢，speed > 1.0 = 更快
generator = pipeline(text, voice='bf_emma', speed=0.85)

all_audio = []
for gs, ps, audio in generator:
    all_audio.append(audio)

import numpy as np
combined = np.concatenate(all_audio)
sf.write('british_slow.wav', combined, 24000)
print(f"Total duration: {len(combined)/24000:.1f}s")
```

### 批量文件处理

处理多段文本并拼接成单个有声书风格的文件：

```python
from kokoro import KPipeline
import soundfile as sf
import numpy as np

pipeline = KPipeline(lang_code='a')

chapters = [
    "第一章。我们的旅程从这里开始。",
    "太阳从群山升起，长长的影子投在山谷上。",
    "她打开门，迈入未知。",
]

all_audio = []
silence = np.zeros(int(24000 * 0.5))  # 章间 0.5 秒静音

for idx, text in enumerate(chapters):
    for gs, ps, audio in pipeline(text, voice='af_bella', speed=1.0):
        all_audio.append(audio)
    all_audio.append(silence)
    print(f"Chapter {idx+1} done")

combined = np.concatenate(all_audio)
sf.write('audiobook.wav', combined, 24000)
print(f"Total: {len(combined)/24000:.1f}s")
```

## 给 Clore.ai 用户的提示

* **CPU 推理** — Kokoro 足够小可以在 CPU 上运行；适用于成本敏感的工作负载或无法使用 GPU 的情况
* **流式传输** — 生成器会随着音频产生而输出音频块，可在 Web 应用中实现实时播放
* **与 WhisperX 结合** — 在语音流水线中使用 WhisperX 进行转录，使用 Kokoro 进行重合成
* **已预装 Docker** — 使用 `pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime` 并添加 `apt-get install -y espeak-ng` 到你的启动项
* **语音一致性** — 在项目中保持使用同一语音 ID，以获得一致的叙述体验
* **成本效率** — 在 RTX 3060 上以 $0.15/天 的成本，Kokoro 是自托管最便宜的 TTS 解决方案之一

## # 使用固定种子以获得一致结果

| 问题                            | 解决方案                                            |
| ----------------------------- | ----------------------------------------------- |
| `未找到 espeak-ng`               | 运行 `apt-get install -y espeak-ng` （必需的系统依赖）     |
| `ModuleNotFoundError: kokoro` | 通过以下方式安装 `pip install kokoro>=0.9.4 soundfile`  |
| 音频听起来很机械                      | 尝试不同的声音（例如， `af_heart` 通常听起来最自然）                |
| 日语/中文 无法使用                    | 安装语言扩展： `pip install misaki[ja]` 或 `misaki[zh]` |
| CPU 内存不足                      | 减少每次调用的文本长度；Kokoro 以块流式输出，使内存保持受限               |
| 第一次运行缓慢                       | 模型权重将在首次使用时下载（约 200 MB）；后续运行将即时可用               |


---

# 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/kokoro-tts.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.
