My Experiments with Voice Generation: Kokoro, Silero, Vosk and Lip Sync from Scratch
I have been obsessed with voice agents all year: latency, turn-taking, interruption. That side gets its own post. This post is about the other half, the voice itself. How does text become sound, what goes wrong, and how far can you get running it all on your own machine?
Most of this came out of building Mark, the talking engineer avatar in my omnitwin project. He runs on a cloud character service by default, and I wanted a fully local mode next to it: local speech recognition, local voice, local lip sync. Getting that to sound and look right took most of my evenings in 2025.
How neural TTS works, in one picture
- Text normalisation. "Dr. Rao meets at 3:30 on 12/05" has to become words. Is it doctor or drive? Twelfth of May or December fifth? This is unglamorous and it is where most embarrassing mistakes come from.
- G2P, grapheme to phoneme. Words become phonemes, usually in IPA. "read" is /riːd/ or /rɛd/ depending on tense. Every language has its own G2P, and for Russian, stress placement is the whole problem.
- Acoustic model. A neural network maps phonemes plus a speaker style to an intermediate representation of sound, historically a mel spectrogram.
- Vocoder. Another network turns that representation into actual audio samples.
- Post-processing. Trim silence, normalise loudness, resample to whatever the player wants.
The mel spectrogram
Almost every TTS and STT model thinks in mel spectrograms, so it is worth knowing what one is. Take short overlapping windows of audio, run an FFT on each, and you get energy per frequency over time. Then squash the frequency axis onto the mel scale, which spaces frequencies the way our ears hear them: fine resolution at low pitch, coarse at high.
mel(f) = 2595 · log10(1 + f / 700)
frame: 512 samples (32 ms at 16 kHz), hop 160 samples (10 ms), 64 to 80 triangular mel filters
The whole thing fits in a few lines of numpy, and writing it once taught me more than reading three papers:
import numpy as np
def mel_spectrogram(audio, sr=16000, n_fft=512, hop=160, n_mels=64):
window = np.hanning(n_fft)
frames = np.array([audio[i:i + n_fft] * window for i in range(0, len(audio) - n_fft, hop)])
power = np.abs(np.fft.rfft(frames, axis=1)) ** 2 # (frames, n_fft/2 + 1)
mel = lambda f: 2595 * np.log10(1 + f / 700)
inv = lambda m: 700 * (10 ** (m / 2595) - 1)
edges = inv(np.linspace(mel(0), mel(sr / 2), n_mels + 2)) # n_mels triangles need n_mels + 2 edges
bins = np.floor((n_fft + 1) * edges / sr).astype(int)
filters = np.zeros((n_mels, n_fft // 2 + 1))
for m in range(1, n_mels + 1):
lo, mid, hi = bins[m - 1], bins[m], bins[m + 1]
filters[m - 1, lo:mid] = (np.arange(lo, mid) - lo) / max(mid - lo, 1)
filters[m - 1, mid:hi] = (hi - np.arange(mid, hi)) / max(hi - mid, 1)
return 10 * np.log10(power @ filters.T + 1e-10).T # (n_mels, frames), in dB
The cover of this post is that function run on a synthetic voiced signal: horizontal bands are the harmonics of the pitch, and the gaps are the pauses between syllables.
Vocoders, and why Kokoro is fast
A mel spectrogram throws away phase, so the vocoder has to invent it. Older neural vocoders generated audio one sample at a time, 24,000 steps per second of speech, which is why early neural TTS was slow. Modern ones generate in parallel. iSTFTNet, the vocoder family Kokoro uses, does not even predict raw samples. It predicts a small STFT, magnitude and phase, and lets a cheap inverse FFT produce the waveform. The network does less work, and the maths does the rest.
x[n] = Σ_m w[n − mH] · IFFT( |X_m| · e^{iφ_m} )[n − mH] (overlap-add of inverse FFT frames)
That is a big part of why Kokoro-82M, released in January 2025, runs comfortably on a CPU. It has 82 million parameters and is built on StyleTTS 2 ideas: the voice is not a fine-tuned model but a style vector, a 256-number embedding that conditions the acoustic model. Change the vector and you change the voice, with the same weights.
Experiment 1: Kokoro in English and Russian
Mark needed to speak English and Russian, because half the people I demo to speak Russian. Kokoro's English voices are excellent out of the box. Russian came from a community fine-tune with its own G2P. Here is the core of what ended up in omnitwin's voice.py, trimmed:
import io
import re
import wave
import numpy as np
from kokoro import KPipeline
KOKORO_SR = 24000
_en = KPipeline(lang_code="a", device="cpu") # "a" = American English
def wav_bytes(audio: np.ndarray, sr: int) -> bytes:
pcm = (np.clip(audio.astype(np.float32), -1.0, 1.0) * 32767).astype(np.int16)
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(sr)
w.writeframes(pcm.tobytes())
return buf.getvalue()
def synth_kokoro_en(text: str, voice: str = "am_adam") -> bytes:
chunks = [audio.numpy() for _, _, audio in _en(text, voice=voice) if audio is not None]
if not chunks:
raise RuntimeError("kokoro produced no audio")
return wav_bytes(np.concatenate(chunks), KOKORO_SR)
KPipeline yields one chunk per sentence-ish segment, which is exactly what you want for streaming. Send each chunk to the player as it arrives instead of concatenating, and the first audio comes back after the first segment, not the whole paragraph.
The Russian path showed me something about how Kokoro works inside. A voice is not one style vector but a pack of them, indexed by the length of the phoneme string:
ipa, _ = ru_g2p(text) # Russian text → IPA phonemes
style = voice_pack[min(len(ipa) - 1, len(voice_pack) - 1)]
audio = kokoro_ru_model(ipa, style, 1.0, return_output=True).audio
Short and long utterances get slightly different style vectors, because a voice is delivered differently in a two-word reply than in a long explanation. When I first ignored this and used one vector for everything, short replies like "Yes, of course" sounded rushed and flat. Picking by length fixed it.
Experiment 2: a fallback chain, because models fail
Local models fail in boring ways: a download times out, a G2P returns empty phonemes for a string of emoji, a model throws on a character it has never seen. A voice agent that goes silent is worse than one with a plainer voice. So synthesis is a chain, routed by language:
def has_cyrillic(text: str) -> bool:
return bool(re.search(r"[а-яА-ЯёЁ]", text))
def synthesize(text: str) -> bytes:
russian = has_cyrillic(text)
engines = [synth_kokoro_ru] if russian else [synth_kokoro_en]
engines.append(synth_silero) # smaller, older, and it has never failed me
for engine in engines:
try:
return engine(text)
except Exception as err:
log.warning("tts engine %s failed: %s", engine.__name__, err)
raise RuntimeError("all TTS engines failed")
Silero TTS is the safety net. It is older and sounds more robotic than Kokoro, but it is small, it loads through torch.hub in one call, and it has never failed on any input I have thrown at it. Routing by script (Cyrillic or not) is crude and works for my two languages. Mixed sentences like "открой Redis dashboard" go to the Russian path, and the Russian G2P spells "Redis" letter by letter. I have accepted that for now.
Experiment 3: listening, with Vosk
For speech recognition I wanted something tiny and offline that could run next to the TTS on a CPU. Whisper is more accurate, but for short commands to an avatar Vosk small models, around 40 to 50 MB each and built on Kaldi, were fast and good enough.
The browser records WebM or Opus. Vosk wants 16 kHz mono 16-bit PCM. ffmpeg bridges the two:
import json
import subprocess
from vosk import KaldiRecognizer, Model
vosk_en = Model("models/vosk-model-small-en-us-0.15")
vosk_ru = Model("models/vosk-model-small-ru-0.22")
def to_pcm16(data: bytes) -> bytes:
result = subprocess.run(
["ffmpeg", "-i", "pipe:0", "-ac", "1", "-ar", "16000", "-f", "s16le", "pipe:1"],
input=data, capture_output=True, check=True,
)
return result.stdout
def recognise(model, pcm: bytes) -> str:
rec = KaldiRecognizer(model, 16000)
for i in range(0, len(pcm), 4000): # feed in small chunks, like a live stream
rec.AcceptWaveform(pcm[i:i + 4000])
return json.loads(rec.FinalResult()).get("text", "").strip()
def transcribe(audio: bytes) -> str:
pcm = to_pcm16(audio)
if len(pcm) < 3200: # under 0.1 s: a click, not speech
return ""
en, ru = recognise(vosk_en, pcm), recognise(vosk_ru, pcm)
return ru if len(ru) > len(en) else en
The language detection at the end is a hack I am a little proud of. Run both recognisers and keep the longer transcript. A recogniser fed the wrong language does not produce a confident wrong sentence. It produces fragments, a word or two it half matched. The right language almost always gives the longer result. When the user picks a language in the UI, I skip the race and only fall back if the preferred model returns nothing.
Experiment 4: lip sync from loudness
A talking avatar with a frozen face is uncanny. A face that moves out of sync is worse. The cloud character service sends real viseme blendshapes, frame by frame. For the local voice I had only a WAV file, so I built the cheapest thing that could work: drive the mouth from the loudness envelope of the audio.
Decode the audio once when it arrives, compute one envelope value per animation frame (60 per second), and look it up by the audio element's current time on every frame:
async function buildEnvelope(data: ArrayBuffer, envRate = 60): Promise<Float32Array> {
const decoded = await new AudioContext().decodeAudioData(data.slice(0))
const pcm = decoded.getChannelData(0)
const hop = Math.max(1, Math.floor(decoded.sampleRate / envRate))
const out = new Float32Array(Math.ceil(pcm.length / hop))
for (let i = 0; i < out.length; i++) {
let sum = 0, peak = 0
const a = i * hop, b = Math.min(pcm.length, a + hop)
for (let j = a; j < b; j++) {
sum += pcm[j] * pcm[j]
peak = Math.max(peak, Math.abs(pcm[j]))
}
out[i] = Math.max(Math.sqrt(sum / (b - a)), peak * 0.55)
}
return out
}
envelope[i] = max( RMS(frame i), 0.55 · peak(frame i) )
level = min(1, 5.2 · envelope) jawOpen = min(0.20, 0.04 + 0.2 · level) (0 when level < 0.035)
Every constant in there came from staring at the avatar:
- Why max of RMS and peak. RMS alone lags on plosives like "p" and "b", which are short and sharp. The scaled peak catches them, so the mouth pops on the consonant instead of a frame late.
- Why such a small jaw range. My first version mapped loudness straight to
jawOpenfrom 0 to 1. Mark looked like he was eating. Real conversational speech barely opens the jaw. Capping it at 0.2 was the single biggest improvement. - Why a silence gate at 0.035. Without it, breath and room noise in the audio kept the lips twitching between sentences.
- Fake vowels. Loudness says how open, not what shape. I add a slow sine over the frame index to alternate between pucker ("oo") and funnel ("ah") shapes. It is a fake, and at conversational distance nobody notices. Real viseme prediction from phonemes is the next step. Kokoro already knows the phonemes and their durations, so the information exists. I just have not wired it through yet.
Measuring: real-time factor
The number I track for every TTS engine is the real-time factor:
RTF = time to synthesise / duration of the audio produced (RTF < 1 means faster than real time)
import io
import time
import wave
def rtf(engine, text: str) -> float:
started = time.perf_counter()
audio = engine(text)
elapsed = time.perf_counter() - started
with wave.open(io.BytesIO(audio)) as w:
seconds = w.getnframes() / w.getframerate()
return elapsed / seconds
On my laptop CPU (8 cores, no GPU), on a set of 40 sentences from real conversations with Mark:
| Engine | Sample rate | RTF, CPU | First audio for a 12-word sentence | My ear |
|---|---|---|---|---|
| Kokoro-82M, English | 24 kHz | about 0.2 | about 350 ms | natural, good prosody |
| Kokoro, Russian fine-tune | 24 kHz | about 0.25 | about 400 ms | good, occasional stress errors |
| Silero v3 English | 48 kHz | about 0.1 | about 200 ms | clear, robotic |
| ElevenLabs Flash (cloud) | 44.1 kHz | n/a | 250 to 400 ms, mostly network | best by a distance |
RTF matters less than it looks once you stream. If the engine produces audio five times faster than real time, the player never runs dry. What the user feels is the first audio, so that is the column I optimise.
A note on voice cloning
The thing everyone asks about first is cloning: give it 30 seconds of someone's voice and it speaks as them. I tried it on my own voice, with an open model and with ElevenLabs' instant cloning, and both were unsettlingly good. I have only ever cloned my own voice, and I think that should be the rule: clone a voice only with the clear consent of its owner, and never use a cloned voice somewhere a listener could mistake it for the real person without being told. The technology to fake a phone call from a family member is now a free download. Building it into a product without consent and disclosure is not a grey area.
What I learned
- Most bad TTS is bad text. Normalise numbers, dates, abbreviations and units before the model sees them. A neural voice reading "12/05" wrong sounds confident and wrong.
- Pick style by utterance length when the model supports it. Short replies need different delivery.
- Always have a fallback engine. Silence is the worst possible voice.
- Run two small recognisers rather than guess the language. The longer transcript wins.
- Lip sync is mostly restraint. A small jaw range, a silence gate, and a peak term for consonants.
- Optimise first audio, not RTF.
My voice repos on GitHub
Everything in this post grew into code that is public on my GitHub:
- omnitwin: the main one. A walkable 3D DevOps lab with Mark, a talking engineer avatar you can interrupt. It has two voice paths: a Convai character with ARKit blendshape lip sync, and a fully local path with Kokoro and Silero for speech, Vosk for recognition, and the envelope lip sync from the second post. The voice backend is
backend/app/voice.pyand the lip sync isweb/src/lipsync.ts. - voice-agent-silero: a Russian-speaking voice consultant for a residential complex, as a website widget. Speech to speech over Gemini Live native audio: 16 kHz PCM from the microphone, 24 kHz PCM back, gapless playback scheduling, and the whole knowledge base in the system instruction.
- ai-avatar-3d: the 3D avatar experiments that came before Mark, with body movement tracking.
- ai-insight-hub: avatar rendering driven by motion, posture and visual recognition. The face and body side of the same obsession.
- chat-bot-ollama: the fully offline chat agent with Ollama and RAG that I use as a local brain when I do not want any cloud in the loop.