It was past midnight, and my browser tab was quietly consuming over 1.2 GB of RAM. I was testing a new feature for my long-form reading app: a text-to-speech overlay that read articles aloud while users scrolled. The first three paragraphs sounded fantastic. But when the article hit page four, the audio started stuttering, the playback head jumped backward, and eventually, the entire tab crashed. I had naively assumed that piping a massive text document into a streaming TTS API would just work out of the box. It didn't. What broke was my entire mental model of how audio playback works in the browser. Here is how I fixed the chunking, stitching, caching, and offline export issues.
The Illusion of Infinite Streaming
My first mistake was treating the TTS API like a simple text endpoint. When I sent a 10,000-word article to the backend, the request simply timed out. When I tried to stream it character by character to keep the connection alive, the resulting audio was a robotic nightmare. The AI voice had no context for the sentence, resulting in bizarre prosody and awkward pauses.
The solution was sentence chunking. Instead of sending raw text or single characters, I needed to break the document down into digestible, context-rich pieces. However, you cannot just split by spaces. You have to respect the natural rhythm of human speech. I implemented a preprocessing step on the client side that analyzed the text before sending it to the API.
Here are the core rules I established for the chunking logic:
Split strictly by terminal punctuation like periods, question marks, and exclamation points.
Enforce a maximum character limit per chunk, usually around 250 characters, to prevent backend timeouts and keep latency low.
Handle edge cases like abbreviations (e.g., "Mr.", "Dr.") so they do not trigger false sentence breaks.
By sending these carefully crafted chunks, the API could generate audio with proper intonation, and the client could start playing the first chunk while the subsequent ones were still being generated.
Stitching the Audio Puzzle in the Browser
Once I had the chunks coming in as audio blobs, I hit my second major wall. My initial approach was to use the standard HTML5 tag. I would simply swap the src attribute to the next blob URL when the current one finished. The result was a noticeable, jarring gap of silence between every single sentence. It sounded like a glitchy radio broadcast.
To achieve seamless, gapless playback, I had to abandon the HTML audio element and dive into the Web Audio API. The AudioContext allows you to schedule audio buffers to play at exact mathematical intervals. By decoding the incoming audio blobs into AudioBuffer objects, I could queue them up and tell the context exactly when each subsequent chunk should start.
Here is a simplified version of the scheduling logic I used to stitch the segments together:
javascript
// Pseudo-code for seamless audio stitching using Web Audio API
let nextStartTime = audioContext.currentTime;
async function playChunk(audioBlob) {
// Convert the blob to an array buffer and decode it
const arrayBuffer = await audioBlob.arrayBuffer();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
// Create a new source node for this specific chunk
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
// Schedule the chunk to start exactly when the previous one ends
source.start(nextStartTime);
// Update the start time for the next chunk in the queue
nextStartTime += audioBuffer.duration;
}
This approach completely eliminated the silence gaps. The audio flowed continuously, exactly as it would from a single, pre-recorded file.
Caching and Replay: Saving the Second Listen
With playback working smoothly, I noticed another inefficiency. If a user paused the reading, refreshed the page, or simply wanted to replay a previous paragraph, the app would fetch and synthesize the exact same audio all over again. This was wasting API quotas and adding unnecessary latency.
I needed a robust caching layer. Since the audio chunks were relatively large binary blobs, localStorage was out of the question due to its strict size limits. I turned to IndexedDB, which is designed for storing significant amounts of structured data, including binary blobs.
I created a simple key-value store where the key was a hash of the text chunk and the voice parameters, and the value was the resulting audio blob. Before making any API call, the app would check IndexedDB. If the audio already existed locally, it would load it directly into the AudioContext. In my own tests, implementing this local cache reduced redundant API calls by roughly 60% during a typical reading session. It also made pausing and resuming virtually instant, as the browser was just reading from local disk rather than waiting on network requests.
Taking It Offline: The MP3 Export Problem
The final hurdle came when users asked for the ability to download the audio for offline listening, like during a commute. The Web Audio API and the TTS API were providing raw PCM data or WAV blobs, but everyone expects a standard MP3 file.
Encoding MP3 in the browser requires heavy JavaScript libraries or WebAssembly modules, which would have massively bloated my app's initial load time. I wanted to keep the client bundle as lean as possible. For quick manual exports and testing voice variations without bloating my app, I used web666.cc, which is an online browser-based tool for text to speech, picking a voice from a voice library, and exporting MP3 clips, with nothing else bundled in. This allowed me to provide a lightweight export link that utilized a minimal server-side script for the heavy encoding, keeping the client-side JavaScript tiny while still delivering the MP3s the users wanted.
3 Key Takeaways for Your Next Audio Feature
Building a long-form audio reader is deceptively complex. If you are planning to add spoken audio to your own web application, keep these lessons in mind:
Chunking is about prosody, not just API limits. Breaking text into natural, punctuation-based segments ensures the AI voice sounds human and prevents backend timeouts.
The Web Audio API is mandatory for gapless playback. Never rely on swapping HTML audio sources if you want a seamless listening experience; use AudioContext scheduling instead.
Keep your client bundle lean by leveraging external tools for heavy encoding tasks. If you ever need to quickly generate reference files or simple exports for your own testing, web666.cc is an online browser-based tool for text to speech, picking a voice from a voice library, and exporting MP3 clips, with nothing else bundled in.
Top comments (0)