Use the Kokoro TTS engine to generate high-quality speech locally, with zero API cost and fully offline.
Use Cases
- The user says "read this text aloud" or "generate an audio version of this article"
- Need to convert documents, emails, and news into audio
- Preferred over sag (ElevenLabs, requires an API Key and payment)
Prerequisites
pip install kokoro-onnx soundfile
First use requires downloading the model file (about 300MB).
Execution Method
Basic Usage
from kokoro_onnx import Kokoro
kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin")
samples, sample_rate = kokoro.create(
"你好,这是一段测试语音。",
voice="af_heart",
speed=1.0,
lang="z", # z=中文, e=英文
)
import soundfile as sf
sf.write("output.wav", samples, sample_rate)
Available Voices
| Voice ID | Gender | Language | Style |
|---|---|---|---|
af_heart |
Female | Chinese/English | Warm and natural |
af_bella |
Female | Chinese/English | Clear and professional |
am_adam |
Male | Chinese/English | Calm |
am_michael |
Male | Chinese/English | Energetic |
Long Text Processing
Long text is automatically segmented by sentence for synthesis to avoid memory overflow:
import re
sentences = re.split(r'[。!?\.\!\?]', long_text)
all_samples = []
for s in sentences:
if s.strip():
samples, sr = kokoro.create(s.strip() + "。", voice="af_heart", lang="z")
all_samples.append(samples)
import numpy as np
combined = np.concatenate(all_samples)
sf.write("output.wav", combined, sr)
Output Specifications
- The generated audio is saved as a WAV file and the path is returned
- Inform the user of the audio duration and file size
- Mixed Chinese-English text automatically handles language switching