Text to Speech in Python: Run Kokoro-82M Locally and Measure It

How do you run text to speech in Python?
To run text to speech in Python, install the kokoro package, let it load the open model Kokoro-82M on your own machine, and save the speech as a WAV file.
It needs no account, key or per-character bill. We tested it on “I read the sign at 10:30.”, a sentence whose letters leave the model a choice. On a MacBook Air M4 the processor made the clip in about a tenth of its playing time (median of 5 runs, Step 5).
Software that does text to speech turns written text into spoken audio. Local TTS runs that software on your own machine, and kokoro is the text to speech Python library for the open Kokoro-82M model.
We describe the chain in four steps. Text normalisation writes digits as words. Grapheme-to-phoneme conversion (G2P) turns the written letters, the graphemes, into phonemes, the smallest sound units. Then the prosody (how long, high and loud each sound is) is set, and a vocoder builds the waveform: the air-pressure values a speaker plays.
In Kokoro, the misaki library does normalisation and G2P; the model does the rest.
How text to speech works walks that chain. Here you run it on “I read the sign at 10:30.”: the letters do not say whether “read” sounds like “reed” or “red”, and “10:30” must become words first.
Step 1: Install kokoro
Use the Python version in the first command: kokoro’s PyPI release allows nothing newer, and the current PyTorch, the deep-learning library under it, supports it:
python3.12 -m venv venv-pypi
. venv-pypi/bin/activate
python -m pip install --upgrade pip
python -m pip install 'kokoro==0.9.4' soundfile
pip also installs misaki, which turns text into phonemes, with a packaged espeak-ng speech engine for words missing from misaki’s dictionary. We installed nothing system-wide. Our exact versions, to pin:
# Top-level (what was asked for)
kokoro==0.9.4
soundfile==0.14.0
# Resolved dependencies that matter for the run
misaki==0.9.4
torch==2.15.0
numpy==2.5.5
spacy==3.8.18
en_core_web_sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl
espeakng-loader==0.2.4
phonemizer-fork==3.3.2
num2words==0.5.14
transformers==5.25.1
huggingface_hub==2.5.0
loguru==0.8.0
Step 2: Synthesize the sentence and save a WAV
speak.py, exactly as it ran:
# speak.py - read one sentence aloud with Kokoro-82M and save a 24 kHz WAV.
import numpy as np
import soundfile as sf
from kokoro import KPipeline
TEXT = "I read the sign at 10:30."
pipeline = KPipeline(lang_code="a", repo_id="hexgrad/Kokoro-82M") # cpu here (no CUDA)
chunks = []
for result in pipeline(TEXT, voice="af_heart"):
print("phonemes:", result.phonemes)
chunks.append(result.audio.numpy())
audio = np.concatenate(chunks)
sf.write("example.wav", audio, 24000)
print(f"saved example.wav: {len(audio)} samples, {len(audio) / 24000:.2f} s")
lang_code="a" (American English) must match the voice af_heart (stored numbers, not a recording). repo_id names the model on Hugging Face. Each result is one chunk of text with its phonemes and audio. sf.write saves the joined chunks at Kokoro’s sample rate (audio values per second).
phonemes: ˌI ɹˈɛd ðə sˈIn æt tˈɛn:θˈɜɹTi.
saved example.wav: 52800 samples, 2.20 s
Step 3 reads these phonemes, in misaki’s own alphabet. The first run also downloads the weights (the numbers the network learned).
Step 3: Read the phonemes it chose
phonemes.py loads no weights (model=False). It prints the graphemes, the phonemes, and each word’s tag from spaCy, misaki’s grammar tagger: VBP present, VBD past, CD number.
# phonemes.py - print what Kokoro's G2P (misaki) does with each sentence.
# model=False: no weights are loaded, only text -> phonemes.
from kokoro import KPipeline
SENTENCES = [
"I read the sign at 10:30.",
"I read the sign every day.",
"Yesterday I read the sign at 10:30.",
]
pipeline = KPipeline(lang_code="a", repo_id="hexgrad/Kokoro-82M", model=False)
for text in SENTENCES:
for result in pipeline(text):
print("graphemes:", result.graphemes)
print("phonemes: ", result.phonemes)
for tok in result.tokens:
print(f" {tok.text!r:12} tag={tok.tag:6} phonemes={tok.phonemes!r}")
print()
Our output, shortened to the lines that matter:
graphemes: I read the sign at 10:30.
phonemes: ˌI ɹˈɛd ðə sˈIn æt tˈɛn:θˈɜɹTi.
'read' tag=VBP phonemes='ɹˈɛd'
'10:30' tag=CD phonemes='tˈɛn:θˈɜɹTi'
graphemes: I read the sign every day.
phonemes: ˌI ɹˈɛd ðə sˈIn ˈɛvəɹi dˈA.
'read' tag=VBP phonemes='ɹˈɛd'
graphemes: Yesterday I read the sign at 10:30.
phonemes: jˈɛstəɹdˌA ˌI ɹˈɛd ðə sˈIn æt tˈɛn:θˈɜɹTi.
'read' tag=VBD phonemes='ɹˈɛd'
“Read” came out as ɹˈɛd (“red”) every time, wrong for the habit in “I read the sign every day.” misaki’s dictionary maps VBP, like VBD, to ɹˈɛd. Listen to such lines before you publish.
“10:30” became tˈɛn:θˈɜɹTi: “ten”, a colon, “thirty”. In misaki’s alphabet some capital letters stand for one vowel sound: I is the vowel of “high”, A the vowel of “hey”. We found no clock-time rule in misaki; write “ten thirty” yourself (advice, not run).
Step 4: Use the Apple GPU with MPS
The PyPI release picks an NVIDIA GPU if present, else the CPU. It never picks MPS, PyTorch’s backend for the Apple Silicon graphics chip, so ask for it:
p = KPipeline(lang_code="a", repo_id="hexgrad/Kokoro-82M", device="mps")
It ran on mps:0.
Step 5: Measure CPU against MPS
The real-time factor (RTF) is compute time divided by audio length; below one, the model speaks faster than it plays. bench.py warms up, then times repeated runs and keeps the median. torch.mps.synchronize() makes the clock wait for the GPU:
def sync():
if DEVICE == "mps":
torch.mps.synchronize()
| MacBook Air M4, 16 GB, Step 1 versions, 2026-12-03; median of 5 runs | CPU | MPS |
|---|---|---|
| Sentence (2.200 s of audio): time, RTF | 0.223 s, 0.101 | 0.153 s, 0.070 |
| 65-word paragraph (21.425 s): time, RTF | 1.968 s, 0.092 | 1.264 s, 0.059 |
| Peak resident memory | 2.78 GB | 1.37 GB |
Both devices made speech far faster than it plays, and MPS was quicker. Resident memory is the most RAM the process held during the run. These are one machine’s numbers; run bench.py (full script below) on yours.
| Mistake | Fix |
|---|---|
No torch.mps.synchronize(): the clock may stop before the GPU is done | Synchronise before reading the clock |
| Timing the first run, which includes setup | Warm up; take the median of several runs |
| A very long venv path: espeak-ng loses its data and exits (error below) | Point ESPEAK_DATA_PATH to a short symlink |
| Comparing CPU and MPS waveforms without a seed: on our example sentence, two unseeded runs on one device already differ almost as much at the largest sample as CPU and MPS do, because the vocoder adds random noise | torch.manual_seed(0); two runs on one device then match |
Error processing file '/Users/runner/work/espeakng-loader/espeakng-loader/espeak-ng/_dynamic/share/espeak-ng-data/phontab': No such file or directory.
ln -s "$VIRTUAL_ENV/lib/python3.12/site-packages/espeakng_loader/espeak-ng-data" ~/espeak-ng-data
export ESPEAK_DATA_PATH=~/espeak-ng-data
If you only wanted to run text to speech in Python, you can stop here.
Step 6: Decide when a hosted API is the better choice
Stay local when Kokoro’s voices cover your text. It has 54 voices in 8 languages, and the voice list in the model repository (VOICES.md) warns that non-English support “may be absent or thin”. The release has no encoder that turns a recording into a voice; it can average its stored voices. Copying a real speaker belongs to voice cloning.
The model’s author put the market rate of Kokoro served over an API at under $1 per million characters of input in April 2025. That is the author’s claim, not our measurement.
For a live voice agent, the user feels the time to the first audio over a stream, and our table does not show it. Kokoro returns audio per chunk: text up to a line break. Our paragraph had no line break, so it was one chunk: its first audio came only at the end.
A hosted API fits when you need other languages or voices, or no model to run yourself. We read three vendors’ pages on 2026-12-03 and sent no request.
Cartesia. The model id is sonic-3.6 (Cartesia Sonic), an update to Sonic 3.5, generally available since 2026-08-27. sonic-3.6 follows the latest stable version; a dated id such as sonic-3.6-2026-08-27 never changes, which suits a pinned build. Cartesia’s pricing page bills per character.
One request is a POST to https://api.cartesia.ai/tts/bytes with model_id, transcript, voice (a voice ID) and output_format. The vendor says first audio arrives in under 90 ms; its page gives no hardware, region or text length.
Google Gemini. The model id is gemini-3.8-flash-tts. Google’s docs call it new, do not label it preview, and say it runs only on the beta API, v1beta. In Python, google-genai 2.25.0 or newer sends one client.interactions.create(...) call with the model, the text and response_format={"type": "audio"}, and gets back a WAV: 24 kHz, mono, 16-bit.
Gemini bills per token. The price per token changes on 2027-01-01, so check it again before you budget; this is the state as of 2026-12-03. Google gives no latency number.
ElevenLabs. ElevenLabs calls eleven_flash_v2_5 its ultra-fast model. One request is a POST to https://api.elevenlabs.io/v1/text-to-speech/{voice_id} with the header xi-api-key and a body of text and model_id; without model_id the API uses eleven_multilingual_v2. Billing is per 1,000 characters.
The ElevenLabs docs give Flash v2.5 a median latency of about 100 ms, without your application or the network; its pricing page says about 75 ms. The vendor’s two pages disagree, so measure in your own path.
Streaming and latency budgets are covered under real-time generation. Which vendor listeners prefer is market news, followed in three text-to-speech strategies of 2026.
What the first run downloads, and the licences
These are the main downloads of our run, not every package. After our run the venv alone took 1.1 GB and the Hugging Face cache 313 MiB.
| What | When it downloads | Size |
|---|---|---|
torch 2.15.0 | pip install | 138.6 MB |
espeakng-loader 0.2.4 | pip install | 9.9 MB |
spacy 3.8.18 | pip install | 6.5 MB |
misaki 0.9.4 | pip install | 3.6 MB |
kokoro 0.9.4 | pip install | 32 kB |
spaCy English model en_core_web_sm 3.8.0 | first KPipeline, by itself | 12.8 MB |
Weights kokoro-v1_0.pth | first KPipeline with the model | 327,212,226 bytes |
Voice voices/af_heart.pt | first synthesis with that voice | 523,425 bytes |
Each voice file downloads only when you first ask for that voice. Our run used Python 3.12.16 on macOS 26.4.1, with espeak-ng 1.52.0 inside espeakng-loader.
The parts carry different licences, as each project states them. kokoro’s code, misaki and the weights are Apache-2.0; the Kokoro-82M model card states the weights’ licence. espeak-ng is GPL v3, and phonemizer-fork, which misaki installs, is GPLv3+. espeakng-loader and spaCy are MIT; num2words is LGPL. We list them; we do not interpret them.
The full script: bench.py
bench.py prints both texts’ times, the real-time factor and peak memory, and saves each waveform for comparison. It calls the pipeline code of the kokoro repository.
Run it as python bench.py cpu, then PYTORCH_ENABLE_MPS_FALLBACK=1 python bench.py mps; the variable sends unsupported operations back to the CPU, and MPS ran without it too.
# bench.py - time Kokoro-82M on one device.
# Usage: python bench.py cpu | PYTORCH_ENABLE_MPS_FALLBACK=1 python bench.py mps
import resource
import statistics
import sys
import time
import numpy as np
import torch
from kokoro import KPipeline
DEVICE = sys.argv[1] # "cpu" or "mps"
RUNS = 5
SR = 24000
TEXTS = {
"example": "I read the sign at 10:30.",
"paragraph": (
"A small open speech model can run on an ordinary laptop. It reads a line of text, "
"turns each word into sounds, decides how long every sound should last, and then "
"builds the waveform one sample at a time. You can test it with a few sentences, "
"listen to the result, and compare how fast it speaks on the processor and on the "
"graphics chip."
),
}
def sync():
if DEVICE == "mps":
torch.mps.synchronize()
t0 = time.perf_counter()
pipeline = KPipeline(lang_code="a", repo_id="hexgrad/Kokoro-82M", device=DEVICE)
pipeline.load_voice("af_heart")
sync()
print(f"device={DEVICE} model_load_s={time.perf_counter() - t0:.2f}")
def synth(text):
"""Return (time to first chunk, total time, audio)."""
chunks, first = [], None
start = time.perf_counter()
for result in pipeline(text, voice="af_heart"):
sync()
if first is None:
first = time.perf_counter() - start
chunks.append(result.audio.numpy())
sync()
return first, time.perf_counter() - start, np.concatenate(chunks)
for name, text in TEXTS.items():
synth(text) # warm-up
firsts, totals = [], []
for _ in range(RUNS):
first, total, audio = synth(text)
firsts.append(first)
totals.append(total)
dur = len(audio) / SR
t = statistics.median(totals)
print(f"{name}: words={len(text.split())} chunks_audio_s={dur:.3f} "
f"first_chunk_s={statistics.median(firsts):.3f} total_s={t:.3f} rtf={t / dur:.3f} "
f"runs_total_s={[round(x, 3) for x in totals]}")
np.save(f"audio-{name}-{DEVICE}.npy", audio)
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # bytes on macOS
print(f"peak_rss_mb={peak / 1024 / 1024:.0f}")
Deploy safe, Max.
Cheat sheet
The article on one page: open it full size, save it or share it.

AI-assisted content, human-reviewed. Images AI-generated. Editorial Standards · Our Editors