Chapter 7
Voice: hear, think, speak
How the assistant listens, knows when you've finished talking, turns speech into text, answers, talks back sentence by sentence, and animates a face that moves with its voice, using open models on your own server.
Two ways to build a voice assistant
| Cascaded (what we built) | Speech-to-speech | |
|---|---|---|
| How | Speech → STT → text → LLM → text → TTS → speech | One model hears audio and produces audio directly |
| Examples | Whisper + any LLM + Kokoro | OpenAI Realtime API, Gemini Live (your key lists gemini-3.8-live) |
| Latency | Seconds (three models in a row) | Sub-second, interruptible mid-word |
| Open source / swappable | Yes: each stage is independent and open | No: one vendor's closed API end to end |
| Reuses your RAG | Directly: the middle step is the same chat pipeline | Needs tool-calling to reach your retrieval |
| Cost | STT/TTS free on your CPU | Billed per audio minute |
You asked for open-source and swappable, and the cascade gets a text transcript for free (voice turns show up in the chat history). The price is latency, which this chapter measures honestly.
The conversation loop
Voice mode starts listening the moment it opens, with "Start talking" under the sphere, like ChatGPT's voice mode. There's no separate "press to talk" step. Two browser rules make that slightly tricky:
- Autoplay policy. Browsers only let a page start audio (an
AudioContext) during a user gesture. So the click on the voice button itself creates and resumes the audio context, before the voice screen even renders:
- Effects run twice in development. React's StrictMode mounts, unmounts and re-mounts components to
flush out effects that don't clean up. The start effect calls
listen()(from a microtask: React's lint rules forbid setting state synchronously inside an effect, andlisten()resets the captions) and returnshaltas its cleanup, and the turn counter (below) makes the first, abandonedlisten()notice it's stale and release the microphone. The same mechanism that handles interruptions handles this.
The rest of the screen is deliberately bare: the sphere (tap it to stop listening, or to interrupt an answer), one line of status, the latest caption, and a round ✕ to go back to the chat. Everything said is also in the chat transcript.
Audio in 90 seconds
- Sound is a list of numbers. A microphone measures air pressure many times per second: the sample rate. 48,000 samples/s from a typical mic; Whisper works at 16,000; Kokoro outputs 24,000. Each sample is a number between −1 and 1 (PCM, the raw form).
- Raw is big. 24,000 samples × 2 bytes = 48 KB per second. Codecs compress it: Opus (Chrome/Firefox) or AAC (Safari) shrink speech ~10× with little audible loss. The mic recording is uploaded as compressed webm/opus; the TTS answer comes back as plain WAV (a 44-byte header + raw PCM), uncompressed but playable everywhere with zero encoding cost.
- Loudness of a stretch of samples is usually measured as RMS (root mean square): √(average of the squared samples). Silence ≈ 0.001, normal speech ≈ 0.02 to 0.2.
Listening: microphone and voice-activity detection
Two browser APIs. MediaRecorder records the mic into a compressed file to upload. The Web Audio API is a graph of audio nodes. We connect the mic to an AnalyserNode, which gives the current waveform and spectrum on demand, without ever routing the mic to the speakers.
echoCancellation: true matters more than it looks: without it, in hands-free mode the mic hears the
assistant's own voice from the speakers and "answers itself".
Voice-activity detection (VAD) answers "is someone speaking?", which tells us when the question is over. Ours is energy-based, every 50 ms:
- For the first 400 ms, measure the room's background loudness (the noise floor).
- Speech threshold = 2.5 × the noise floor (at least 0.012).
- Three loud frames in a row (150 ms) = speech started (a single click isn't speech).
- After speech, 1.2 s below the threshold = the visitor finished. Stop and upload.
- Nothing for 8 s = give up politely. 30 s = hard cap.
The 1.2 s is a trade-off: shorter cuts people off mid-thought, longer feels sluggish. A neural VAD like Silero (a ~2 MB model that runs in the browser via vad-web) tells speech from noise far better in noisy rooms.
Speech to text: Whisper
Whisper is OpenAI's open-weights speech recognizer, a
transformer trained on 680,000 hours of audio. We run the base.en size (74M parameters, English-only)
through faster-whisper, a reimplementation on
CTranslate2 (an inference engine for transformers) with int8 quantization: weights stored as 8-bit
integers instead of 32-bit floats, 4× smaller and much faster on CPU, with a tiny accuracy cost.
beam_size=1: greedy decoding (always take the most likely next token). Fastest, and nearly as good as beam search on short clips.vad_filter=True: Silero VAD (bundled) cuts silence before recognition. Whisper invents words in silence ("Thank you for watching!", a known artifact of its YouTube-heavy training data).initial_prompt: text Whisper treats as "what was said just before", which biases its vocabulary.
The first end-to-end voice test asked "What did Amine build during his internship at Drivago?". Whisper heard "Dravago". Search found nothing about "Dravago", and the assistant (correctly!) said it had no information. The vocabulary hint existed but was built from page titles cut at the first parenthesis, which dropped "…at Drivago". Fixed by collecting every capitalized name from the titles plus key terms:
After the fix, the same audio came back as "Drivago", and "EVMirror and DeepVolt" also transcribed exactly. Proper nouns are speech recognition's weak spot; prompt biasing is the cheap fix. Note how an STT error turned into a retrieval failure: in a cascade, errors flow downstream.
The first transcription crashed with TypeError: open() got an unexpected keyword argument
'metadata_errors'. faster-whisper uses PyAV to decode audio, and PyAV 19 (released recently) removed that
argument. Fix: pin av<19 in pyproject.toml (with a comment saying why). Pin the
dependencies you don't control, and leave a note so future-you knows when it's safe to unpin.
Text to speech: Kokoro
Kokoro-82M is an open-weights TTS model with only 82 million parameters that sounds close to commercial voices. Text is first converted to phonemes (how it's pronounced, via espeak-ng: "Drivago" → /dɹɪvˈɑːɡoʊ/), then the network generates the waveform in a chosen voice. We run the ONNX export through kokoro-onnx.
The first measurement was disappointing: ~1.2 s of compute per second of speech. That's a real-time factor (RTF) of 1.2, slower than real time. The culprit was threading. ONNX Runtime defaults to one thread per logical core (20 on this laptop, which mixes fast and slow cores); threads waiting on each other cost more than they gained. Measured on one sentence:
| Threads | 1 | 4 | 6 | 8 | 12 | 20 (default) |
|---|---|---|---|---|---|---|
| RTF (lower is better) | 2.82 | 0.89 | 0.68 | 0.61 | 1.04 | 1.30 |
The int8, fp16 and fp32 versions of the model all landed between RTF 0.55 and 0.71 at 8 threads, so we keep the smallest
(int8, 88 MB). Now ONNX_THREADS=8 is a setting. On a 2-vCPU server, expect RTF above 1, which means the
next option below.
Before synthesis, speakable() strips what shouldn't be read aloud (citation markers, URLs, markdown
symbols) and expands a few things ("R²" → "R squared"). The LLM is also told it's in voice mode: at most 3 short
sentences, no lists, no links, numbers said the way a person would.
Speaking before the answer is finished
Waiting for the whole answer, then synthesizing it all, would add many seconds of silence. Instead the browser
splits the streaming text into sentences and sends each to /api/tts as soon as it's complete, while the
model is still writing:
LLM: [sentence 1 ][sentence 2 ][sentence 3] TTS: [synth 1 ][synth 2 ][synth 3] play: [play 1 ][play 2 ][play 3]
A sentence ends at .!? followed by whitespace, so "1.2 s" doesn't split, and "e.g." is skipped. The
first piece may also be cut at a comma once it's 70+ characters, because time to first sound is what the
listener notices most. The Speaker fetches audio at most two sentences ahead, decodes it, and plays the
pieces strictly in order through an analyser:
If the server has TTS disabled, the Speaker falls back to the browser's built-in speechSynthesis.
That's free and instant, but the voices vary by OS and Web Audio can't "hear" them, so the orb's movement is
simulated in that case.
The honest latency budget
| Stage | Measured on this laptop | How to cut it |
|---|---|---|
| Waiting for silence (VAD) | 1.2 s | Neural VAD + shorter hangover; push-to-talk |
| Upload + Whisper | ~1 to 1.5 s | GPU; Groq's hosted Whisper (STT_PROVIDER=openai) |
| LLM to first sentence | ~2 to 5 s (free tier) | Faster provider (Groq), paid tier, shorter prompt |
| Kokoro, first sentence | ~1.5 to 3 s | GPU; streaming TTS; shorter first clause |
| First sound | ~6 to 10 s | Speech-to-speech models: under 1 s |
That's acceptable for a portfolio demo and very educational, but it's why commercial voice assistants moved to speech-to-speech. Every stage here is swappable, so you can attack each row separately and measure.
Turn-taking and interruptions
Async code plus interruptions is a classic bug factory: you interrupt an answer, start a new question, and then the old answer's last sentence finishes downloading and starts talking over the new one. The fix is a turn counter. Every new turn increments it; every async step remembers the number it started with and quietly stops if it changed:
That's why finish(myTurn) checks turn.current !== myTurn after every await.
It's the same idea as request cancellation tokens and "generation" counters in game loops.
The orb
The animated "face" is ~150 lines of canvas code, no library, in the same neural-network style as your hero section:
- Points on a sphere. A Fibonacci sphere spreads 120 points evenly: step down the y-axis evenly while rotating each point by the golden angle (≈137.5°) around it. Each point is linked to its 3 nearest neighbours, precomputed once.
- 3D → 2D. Every frame, rotate the points around the y-axis (spin) and the x-axis (fixed tilt) with the standard rotation formulas, then project with simple perspective: points with larger z (closer) are drawn slightly larger and brighter, farther ones fade.
- Audio drives the shape. The analyser gives 32 frequency bands, log-spaced because speech energy is concentrated in low frequencies. Each point listens to one band and is pushed outward by its energy, so different parts of the sphere ripple with different parts of the voice. Overall loudness swells the whole sphere and brightens the glow, smoothed with an exponential moving average so it doesn't jitter.
- States change colour and motion: cyan with a pulse ring while listening (driven by
your mic), violet with orbiting arcs and a sweeping band while thinking, blue while speaking (driven by
its voice). Colours come from the site's CSS variables, so it follows the light/dark theme, and it stops
rotating under
prefers-reduced-motion.
I can't speak into your laptop, so the end-to-end test replaced the browser's microphone with a fake one: in the
page console, navigator.mediaDevices.getUserMedia was overridden to return a stream that plays a WAV
spoken by Kokoro ("What did Amine build during his internship at Drivago?"), after 700 ms of silence so
the VAD could measure the noise floor. The real code then ran: VAD detected speech and silence, MediaRecorder uploaded
it, Whisper transcribed it, RAG answered, Kokoro spoke, and the orb animated. That's how the "Dravago" bug was found.
Faking an input at the boundary is a powerful testing trick: you can test a voice app with no voice.
Why does the orb only truly react to the assistant's voice when the server does TTS, and not with the browser's speechSynthesis fallback?
You can only analyse audio you route through your own audio graph. That's a real, practical reason to prefer server-side (or Web-Audio-played) TTS when you want visual feedback.
A visitor interrupts an answer and asks a new question. The old answer's next sentence finishes downloading a moment later. Why doesn't it play?
Belt and braces: abort what you can (AbortController), and make every async continuation check it still belongs to the current turn.
ONNX Runtime ran Kokoro faster with 8 threads than with 20 on a 20-thread CPU. The most likely explanation?
Thread count is a tuning knob, not "more is better". Measure on the machine that will actually run it, because your server's best value will differ.
Go further
- paperWhisper: Robust Speech Recognition via Large-Scale Weak Supervision
- modelKokoro-82M Voices list (try
TTS_VOICE=am_michaelorbf_emma). - docsMDN: Visualizations with Web Audio API The AnalyserNode technique the orb uses.
- docsMDN: MediaRecorder
- frameworkPipecat An open-source framework for exactly this kind of cascaded voice agent, with streaming at every stage.
- docsGemini Live API The speech-to-speech alternative, worth a weekend experiment.
- articleEvenly distributing points on a sphere The Fibonacci lattice the orb uses, and how to do better.