Vineet Ganti
Listen to this post: the browser voice
All posts

Build Logs/Building this site · Part 3 of 9

·16 min read

Listen to this post: the browser voice

Part 3 of the build log for this site. Every post can be read aloud by the browser's own text-to-speech: what gets read, the state machine that keeps pause and skip honest, the four fixes that made it work on phones, and the bug where a hidden page kept its player saying playing. It ends with the short history of the AI podcast versions, which were removed on 2026-11-18.

Web Speech APIAudioReact

The posts on this site are long: the old build-log post took about 31 minutes to listen to, and some database posts take longer. So every post has a Listen to this post button, which has the browser read the post aloud. This part explains how that player works and re-measures what it does today, which found one thing to fix and one thing the original write-up got wrong. For five days the site also had recorded AI podcast versions; the last section says what they were and that they are gone.

#TL;DR

  • Every post can be read aloud by the browser with the Web Speech API. It reads the rendered prose and each diagram's description, and says "Code example skipped" or "Table skipped" instead of reading code and tables.
  • A generation counter keeps pause, skip and speed changes reliable: every speak call takes a new number, and a late end event from an older utterance does nothing.
  • Phones needed four fixes and a watchdog. They were tested in an emulated phone with a stubbed speech engine, never on a real handset.
  • ✅ Next keeps the previous page alive but hidden. Leaving a post mid-sentence stopped the speech, but coming back showed "Stop listening" while nothing was spoken, until the cleanup also reset the player's state.
  • ✅ A correction: the player was described as keeping every spoken chunk under 180 characters. It doesn't: the longest chunk sent in today's test was 327 characters, because a single long sentence is never split.
  • The AI podcast versions are gone. Fourteen NotebookLM recordings had their own pages from 2026-11-13; on 2026-11-18 the pages, the player and the files were removed.

#The browser voice

#Why not pre-generated audio for everything?

Browser voicePre-generated files
CostFreeA text-to-speech service per post, and again after every edit
New postsWork at onceNeed a generation step
Voice qualityDepends on the deviceConsistent
Download, lock-screen playNoYes

The free option covers every post on the day it is published, and it changes whenever the post does.

#What gets read

DataRequest or acknowledgmentMetadata

The logic is in src/lib/speech.ts, kept apart from React so it can be tested on its own. It reads the rendered page (#post-content), not the Markdown, for two reasons: each chunk keeps a reference to its element so it can be highlighted, and whatever the page shows, including text from components, is what gets spoken.

tssrc/lib/speech.ts (shortened)
const SKIPPED: Record<string, string> = {
  PRE: "Code example skipped.",
  TABLE: "Table skipped.",
  IMG: "Diagram skipped.",
  DETAILS: "Recall questions skipped.",
};
const SKIP_CONTAINERS = "pre,table,details,.diagram";
const READ_SELECTOR = "h2,h3,h4,p,li,pre,table,img,.diagram,details";
const MAX_CHUNK = 180;

Each rule exists because of how speech sounds:

  • Symbols are rewritten. → becomes "to", × becomes "times", and dashes become commas; otherwise a voice says "rightwards arrow".
  • Sentences split at punctuation followed by a space, with the lookbehind /(?<=[.!?])\s+/, so "1.5×" stays whole.
  • Diagrams are read from their alt text, after the word "Image:". An alt counts as a description only if it has at least 12 characters and a space, so a file name such as flow_chart gets the skip note instead. Interactive charts carry the diagram class too, so they are read from their aria-label. That makes alt text matter twice, for screen readers and for this player, and there is a setting to turn diagram reading off.
  • A run of the same skipped kind gets one note, not one per block.

#A correction: the 180-character limit

The original write-up said chunks are capped at 180 characters, because some browsers are widely reported to cut off a long utterance after about 15 seconds. ⚠️ That cut-off is a known Chromium behaviour discussed in bug reports, not something the specification documents, so treat it as reported rather than verified.

The cap is real in the code, but it only applies when joining sentences: splitForSpeech adds sentences to a chunk while the total stays under 180, and a sentence that is longer on its own is sent whole. To see what the player really sends, I played four posts through the real page with the speech engine replaced by a stub that records each utterance and ends it 2 ms later:

PostChunksWords spokenSkip notesDiagrams readLongest chunk
MapReduce162261 code0327 characters
SQL foundations2331,8742 code, 31 table, 29 recall1320
Transactions and ACID2714,5934 code, 6 table, 1 recall20247
The old build-log post3235,08319 code, 19 table, 1 recall9272

✅ Measured on 2026-11-13 in headless Edge on the dev server. Every run finished on its own.

So four of four posts sent chunks over the target, up to 1.8 times it. A 327-character sentence is about 55 words, roughly 20 seconds at normal speed. If a browser does cut long utterances off, the watchdog notices the engine went quiet without an end event and moves to the next chunk, so a listener would lose the end of that sentence rather than get stuck. The fix would be a second split at commas for over-long sentences. It isn't made yet.

#The player: a small state machine

AudioPlayer.tsx is a client component. Four decisions carry it.

Browser facts come from useSyncExternalStore. Whether the browser can speak, and which voices it has, are outside React. Voices arrive late, on a voiceschanged event, so the component subscribes to it. On the server the store returns "nothing", so the server and the first browser render match.

Pause is "cancel and remember". speechSynthesis.pause() is unreliable in some browsers, so pausing cancels the utterance and resuming starts that chunk again. A new speed or voice does the same: restart the current chunk with the new setting.

A generation counter stops stale callbacks. Cancelling an utterance can still fire its onend, which would start the next chunk and undo the pause:

tssrc/components/AudioPlayer.tsx (shortened)
const speak = (i: number) => {
  const gen = ++genRef.current; // a new generation invalidates every older callback
  // ...highlight chunk i, update state...
  const utterance = new SpeechSynthesisUtterance(chunks[i].text);
  utterance.rate = prefsRef.current.rate;
  utterance.onend = () => {
    if (genRef.current === gen) speakRef.current(i + 1); // only if nothing newer started
  };
  synth.speak(utterance);
};

One number compared in one place is easier to keep right than a "paused" flag that every code path must remember to reset.

Highlighting scrolls only when it must. The block being read gets a tts-active class, and it is scrolled into view only if it drifts under the sticky header or the player bar, instantly when the reader prefers reduced motion. Speed and voice are saved in localStorage inside try/catch, because storage can be blocked.

The player on desktop: a bottom bar with previous, pause and next buttons, Playing, the time left, a speed button, a settings button and a progress bar, while the paragraph being read is highlighted above it

#Making it work on phones

📜 After the first release, the player didn't speak on phones, in Safari or Chrome. I couldn't hold a phone to the code, so the code was read for the failure points known to hit mobile browsers, and four were real:

Symptom on a phoneCause in the codeFix
Nothing is spokencancel() and speak() in the same instant; mobile browsers can drop speech queued like thatCancel only when something is speaking, and wait 80 ms before speaking after a cancel
One sentence, then silenceThe utterance object wasn't kept anywhere, and it can be garbage-collected mid-speech, so its end event never firesKeep the current utterance in a ref
Silent after a pauseMobile Chrome can leave the engine "paused"Call resume() before every speak()
"Paused", with no reasonA failed utterance was caught and ignoredShow the reason in the bar

Two safety nets sit on top. A watchdog checks every 500 ms: if speech started but the engine went idle without an end event, it moves on; if nothing started within 4.5 seconds, it stops and says "Nothing was spoken. Check the volume (and the silent switch on iPhone), then tap play again". And a browser that blocks audio gets a plain message instead of silence. The first tap still calls speak() inside the click handler, because phones only allow speech that a tap starts, and the bar sits above the iPhone home indicator with env(safe-area-inset-bottom).

#Leaving a page that is still talking

This version of Next.js, with Cache Components on, doesn't unmount a page when you navigate away. It hides it with React's <Activity>, which keeps the DOM in the page with display: none (Preserving UI state). Effect cleanups still run when a page is hidden, as they do on unmount, so anything that keeps running has to be stopped in one.

✅ With a stubbed speech engine, on 2026-11-13: the speech was already cancelled when leaving, because the player's cleanup called speechSynthesis.cancel(). But coming back showed "Stop listening" and a Pause button while nothing was speaking. The cleanup stopped the engine and left the player's own state saying "playing". It now resets that state in the same cleanup.

What I'd do differently: search the docs for "hidden" or "preserving state" before writing anything that keeps running after a click. The guide has a section on exactly this.

#What happened to the AI podcasts

📜 From 2026-11-13 to 2026-11-18 fourteen posts also had an AI podcast version: a two-host NotebookLM Audio Overview of the post, 41 to 70 minutes long. The files were re-encoded to mono AAC at 64 kbps and stored in Vercel Blob (390.6 MB, 39% of the free plan's 1 GB), and they had their own /podcasts pages with one shared player, so a post kept its browser voice and only linked to its episode. Building that player taught the lesson above in a stronger form: a hidden <audio> element keeps playing, with its controls hidden too, so the podcast player paused itself in a layout-effect cleanup.

On 2026-11-18 the podcasts were removed: the pages, the player, the episode link on each post, the two lists that named the recordings, the upload scripts, and the fourteen files in Blob. Two reasons to be careful with recordings like these stay true: the hosts paraphrase, so a recording can say something the post doesn't, and it goes stale the moment the post is edited.

#Things that can trip you up

  • An alt text that is a file name. The player skips it, and so do screen readers in effect. Write alt text as a description.
  • Essential content in a table or code block only. The browser voice skips it. Say the important point in prose too.
  • Testing speech on a laptop only. Phones differ: speech must start from a tap, and events can go missing.
  • Testing only what happens when a page opens. With Cache Components, a page you leave is hidden, not removed, so anything that keeps running (speech, audio, timers, subscriptions) keeps running, and state can be left saying it still is. Test leaving and coming back.

#Reproduce this yourself

  1. ✅ Play a post with a stubbed voice. In a headless browser, replace window.speechSynthesis before the page loads with an object whose speak records utterance.text and calls onend a moment later, press Listen to this post, and read the recorded list. That is how the table above was made.
  2. ✅ Test leaving. With the same stub, start a post, click a link to another page, then press Back. The engine should be silent and the button should say Listen to this post again.
  3. 📘 Read the API. SpeechSynthesis on MDN lists the methods and events the player relies on.

#Summary

Every post can be listened to for free: the browser voice reads the rendered prose and diagram descriptions, says what it skips, and stays reliable through pauses and skips because each speak call takes a generation number. Phones needed four fixes and a watchdog, tested only in emulation. Re-measuring found two things to act on: a hidden page left the player saying it was playing (fixed), and chunks can exceed the 180-character target (not fixed yet). The AI podcast versions that ran beside it for five days are removed.

#Key takeaways

  • Read the rendered page, not the source, when the output should match what readers see.
  • A generation number beats a flag for "is this callback still wanted?".
  • A limit that is applied only when joining things is not a limit on each thing.
  • Test leaving as well as arriving: a framework that hides pages instead of removing them keeps whatever they started running.

#Concepts at a glance

TermIn one line
Web Speech APIThe browser's built-in speech; SpeechSynthesisUtterance is one thing to say
collectChunksTurns the rendered post into short speakable pieces with skip notes
Generation counterA number each speak takes, so older callbacks can tell they are stale
WatchdogA timer that notices speech that never started or never ended
ActivityReact's component that hides a page with display: none and keeps its state; Next uses it to keep the previous page

#Test yourself

Why does pausing cancel the utterance instead of calling pause()?

speechSynthesis.pause() is unreliable in some browsers. Cancelling and restarting the chunk on resume behaves the same everywhere, at the cost of repeating the start of one chunk.

A reader pauses, and the next paragraph starts anyway. What is the likely cause, and the fix here?

The cancelled utterance fired its end event, which started the next chunk. Each speak takes a new generation number and pause bumps it, so a callback from an older generation does nothing.

Why did the player send a 327-character chunk when the limit is 180?

The limit applies when joining sentences. A single sentence longer than 180 characters is sent whole, because nothing splits inside a sentence.

A post is being read aloud and you click a link. Coming back, the bar says "Stop listening" but nothing is speaking. Why?

Next hides the page you left with display: none instead of removing it. The player's cleanup ran and cancelled the speech, but it left the player's own state saying "playing". The fix resets that state in the same cleanup.

#Sources