Prompt
How do I stream TTS audio to the browser as it generates?
Latest observation
To stream TTS audio to the browser as it generates, you generally need to:
- Generate audio in chunks on the server
- Send those chunks over a streaming HTTP response or WebSocket
- Play them incrementally in the browser
The exact best approach depends on whether your TTS engine can output partial PCM/MP3/Ogg data continuously, or only returns a complete file.
Recommended approach
Option A: HTTP streaming + MediaSource Extensions (best for browser playback)
If your TTS model can emit chunks of audio data, your backend can stream them with chunked transfer encoding.
Server flow:
- Receive text
- Start generating audio frames/chunks
- Write chunks to response immediately
Browser flow:
- Use
fetch()with streamingReadableStream - Append incoming bytes to a
MediaSourceSourceBuffer - Play as data arrives
This works best if your audio format is something the browser can append incrementally, such as:
- WebM/Opus
- MPEG audio
- sometimes fragmented MP4
Example backend idea
app.post('/tts', async (req, res) => {
res.setHeader('Content-Type', 'audio/mpeg');
res.setHeader('Transfer-Encoding', 'chunked');
for await (const chunk of generateTTSChunks(req.body.text)) {
res.write(chunk);
}
res.end();
});
Option B: WebSocket streaming
If you want lower-latency bidirectional communication:
- Use WebSocket
- Send audio chunks as binary frames
- Browser buffers and plays them
This is common when:
- You need progress updates
- You want to cancel generation mid-way
- You’re controlling multiple real-time events
But playback is harder than HTTP streaming unless you still use a browser media pipeline.
Option C: Stream raw PCM and play with Web Audio API
If your TTS backend can output raw PCM frames, the browser can:
- receive them over fetch/WebSocket
- decode or wrap them
- schedule playback with the Web Audio API
This gives you the most control, but it’s more work because the browser doesn’t natively “play raw PCM stream” via <audio>.
Important caveat: format matters
Not every audio format streams nicely in browsers.
Good streaming formats
- WebM/Opus
- Ogg/Opus
- fragmented MP4
- MPEG audio in some cases
Harder formats
- WAV: usually needs a correct header and often the final file length
- MP3: sometimes playable as a stream, but browser behavior varies
- Raw PCM: not directly playable in
<audio>
If your TTS provider only returns a complete WAV/MP3 at the end, you can’t truly “play while generating” unless you transcode or ask the model/provider for incremental output.
Simple practical pattern
Backend
Use a streaming endpoint:
Content-Type: audio/webmoraudio/mpeg- write audio chunks as they’re produced
Frontend
Simplest case: if the browser can play streamed audio directly, just point audio to the endpoint:
<audio controls autoplay src="/tts?text=Hello"></audio>
If that doesn’t buffer/play early enough, switch to:
fetch()ReadableStreamMediaSource
Minimal browser example with fetch stream
const response = await fetch('/tts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'Hello world' })
});
const reader = response.body.getReader();
const chunks = [];
while (true) {
const { value, done } = await reader.read();
if (done) break;
chunks.push(value);
// You would append these to a MediaSource buffer here
}
Note: collecting chunks in an array alone does not stream playback. You need a playback pipeline such as MediaSource.
If you want the easiest working solution
If you control the TTS backend, the easiest robust setup is:
- Generate audio in Opus/WebM fragments
- Serve them with chunked HTTP
- Append to a MediaSource buffer in the browser
If you tell me your stack, I can give you exact code
If you want, I can provide a working example for one of these:
- Node.js + browser MediaSource
- Python FastAPI streaming audio
- WebSocket TTS streaming
- Raw PCM + Web Audio API
- Using a specific TTS provider like OpenAI / ElevenLabs / Azure / Google
If you share your backend language and the TTS engine you’re using, I’ll tailor the implementation.