FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Streaming Audio Decoding and Browser Playback

Decode timestamped audio packets in browsers, schedule PCM frames on the Web Audio clock, and bound playback lead to absorb jitter without hiding delay.

Freshness: current•12 min read•AI User Experience and Human-AI Interaction
Full Technical Reference Document

Mental model

Incremental browser audio playback is a paced pipeline: the transport yields complete codec packets with timestamps, WebCodecs decodes them in order, and Web Audio schedules decoded frames against the audio clock. A bounded lead between the decoder and playback clock absorbs network jitter; it also gives the reader a precise point to pause, cancel, or report underrun.

The packet boundary is a codec boundary, not an arbitrary TCP or Fetch chunk. A network read may split one compressed packet or contain several. The transport adapter must reconstruct packet framing before creating an EncodedAudioChunk; otherwise a byte fragment can be mistaken for a complete frame and decoding fails or produces a gap. Keep packet sequence, presentation timestamp, duration, and payload together through that adapter.

Theory

There are two queues with different clocks. AudioDecoder.decodeQueueSize measures encoded work submitted to the browser decoder but not yet processed. The playback lead measures already-decoded audio scheduled ahead of AudioContext.currentTime. A low decoder queue does not prove smooth playback: the network might still be late. A full decoder queue does not mean the listener hears that audio yet. Monitor both, along with packet arrival gaps and underruns.

AudioDecoder accepts complete encoded chunks carrying media timestamps in microseconds and emits AudioData frames asynchronously. Configuration names the codec and its sample rate and channel count; codec initialization bytes belong in description when that codec requires them. A sender and receiver must agree on codec, framing, timestamp origin, and discontinuity rules. AudioData.timestamp is media time, whereas AudioContext.currentTime is the browser's render clock. They cannot be compared directly without an anchor mapping the first media timestamp to a scheduled context time.

The standards describe APIs; they do not promise that a particular browser build supports every codec configuration. Web Audio API 1.1 is still a W3C Working Draft, and WebCodecs availability and codec support vary by engine. Call AudioDecoder.isConfigSupported() for the exact configuration at runtime, test real target devices, and keep a tested fallback such as a server-provided supported format or non-streaming playback.

decodeAudioData() is useful for decoding a complete audio resource. Calling it independently on arbitrary pieces of a continuous compressed stream discards the streaming decoder state and usually fails because a piece is not a complete file. WebCodecs provides the packet-oriented path. After decoding, convert each output frame into the representation used by the player, preserve channel count and sample rate, and schedule it on the audio clock. The browser may produce frames later than the decode() call, so keep output handling serialized; otherwise asynchronous copies can finish out of order and reverse audible chunks.

For moderate-latency speech playback, a scheduled AudioBufferSourceNode per decoded frame is straightforward. Start each node slightly in the future and place it no earlier than the end of the preceding node. For very small frames or sustained high throughput, per-frame AudioBuffer allocation and node creation create avoidable garbage and scheduling work. An AudioWorklet fed by a bounded ring buffer gives a steadier render path, but requires explicit write/read indices, underflow behavior, and often SharedArrayBuffer isolation headers. The simpler path is often the right first design when its measured allocation rate and latency meet the product budget.

Quantitative model

Choose a startup buffer from measured excess arrival jitter, decoder latency, a render safety margin, and the media duration of one packet:

N=⌈J95+D95+MC⌉,B=N CN = \left\lceil\frac{J_{95}+D_{95}+M}{C}\right\rceil,\qquad B=N\,C

Here J95 is the 95th-percentile positive packet-arrival delay beyond the expected cadence, in milliseconds; D95 is decoder p95 latency in milliseconds; M is a scheduling margin in milliseconds; C is one packet's media duration in milliseconds; N is the integer number of packets buffered before playback; and B is the resulting startup buffer in milliseconds. This is a starting estimate, not a guarantee: track actual underruns and tune the lead under the network and device conditions that matter.

For 20 ms packets, a measured J95 of 65 ms, decoder D95 of 4 ms, and a 12 ms render margin give N = ceil((65 + 4 + 12) / 20) = 5 packets, or B = 100 ms. The extra 19 ms is the packet-granularity rounding cost. If the product's speech-start target cannot tolerate 100 ms, do not pretend that a smaller queue can absorb the same jitter. Improve transport variance, use a codec and frame duration appropriate to the workload, or accept and measure more underruns.

Reassemble timestamped codec packet
Bound decoder submissions
Decode to AudioData
Copy samples into playback buffer
Schedule against AudioContext clock
Conceptual teaching model synthesized from:webcodecs-spec,webcodecs-opus-codec-registration,web-audio-api-spec

Trade-offs

The main control is how much media time may sit ahead of the listener. A larger lead masks bursty delivery and short decoder stalls, but delays the first audible sample and makes cancellation take longer to become perceptible. A smaller lead reduces response latency but leaves less time to recover from network jitter. Expose pause and stop controls that cancel scheduled sources or reset the worklet ring; simply stopping network reads does not retract audio already handed to the render thread.

Timestamping is more useful than counting received packets. A missing sequence number reveals loss, while a timestamp discontinuity reveals a media-time gap even if packets arrived in order. For real-time speech, the application must choose whether to wait, conceal the missing audio with codec-supported behavior, or skip to a later timestamp. Waiting forever turns one lost packet into growing latency. Silently concatenating later samples compresses time and can make speech sound wrong. State which policy applies and surface a reconnect or degraded-audio status when recovery exceeds its budget.

Failure modes and misconceptions

  • Treating transport reads as codec frames: Fetch and socket chunks are delivery units. Parse the wire format first, then pass only complete codec packets to the decoder.
  • Using the wrong clock: Media timestamps order the stream; AudioContext.currentTime schedules playback. Anchor them once per stream and reset that mapping after a seek, reconnect, or timestamp discontinuity.
  • Scheduling the whole response at once: This turns streaming into delayed file playback and can allocate seconds of PCM before the first sound. Keep a bounded media-time lead and pause the producer when it is full.
  • Letting decode output callbacks race: copyTo() is asynchronous. Serialize frame conversion and scheduling, and close every AudioData object after copying so decoder-owned memory can be reclaimed.
  • Ignoring browser startup policy: An AudioContext may begin suspended until a user gesture resumes it. Start or resume it from the play action and show that state instead of reporting a false decoder failure.
  • Assuming the codec repairs all gaps: A decoder cannot infer an application's packet sequence and retransmission policy. Test reordered, lost, duplicated, late, and malformed packets at the framing layer as well as decoder errors.

An operational dashboard should pair first-audible latency and p95 playback lead with underrun count, decoder queue depth, dropped or late packets, and decode errors. A rising lead with no underruns points to unnecessary buffering; a falling lead with repeated underruns points to insufficient margin or upstream jitter. These signals separate a transport problem from a scheduling problem.

Decision scenario

A voice assistant emits 20 ms Opus packets. A device test measures 65 ms p95 excess arrival jitter, 4 ms p95 decode latency, and a 12 ms scheduling margin. The five-packet estimate yields 100 ms of startup buffering. If the product can accept that first-audio delay, start after five complete packets and cap the queued lead near the measured target. If it cannot, keep the latency requirement visible and improve delivery variance or test a lower-latency framing choice; reducing the buffer without measuring the resulting underrun rate only moves the failure to the listener.

During playback, stop reading more packets while the decoder queue or queued media-time lead reaches its cap. Resume after scheduled audio drains below a low-water mark. For a push-only transport that cannot be paused, add a bounded application queue and define which stale packets to discard after a stall; never allow unbounded compressed or decoded audio to accumulate behind the listener.

Learning outcomes

  • Distinguish arbitrary transport chunks, complete encoded audio packets, decoded AudioData, and scheduled Web Audio buffers.
  • Convert packet duration, p95 jitter, decode latency, and safety margin into a measured startup-buffer estimate.
  • Diagnose whether an underrun comes from delivery, decoder backlog, clock mapping, or playback scheduling.
  • Choose between scheduled buffer sources and an AudioWorklet ring buffer using measured latency and allocation needs.

Implementation pattern

The example expects packet to contain one complete Opus packet with bytes, timestampUs, and durationUs. The Opus WebCodecs registration requires its encoded audio chunks to use type key; this type does not express a video-style key-frame boundary. A caller should await waitForCapacity() before reading the next packet from a pull-based stream. Resume the context in response to the user's play action, and validate AudioDecoder.isConfigSupported() before configuring the decoder.

javascript
function createPacketAudioPlayer(context, config, onError) {
let queuedSeconds = 0, nextStart = 0, mediaAnchorUs = null, contextAnchor = 0;
let outputChain = Promise.resolve();
const sources = new Set();
const decoder = new AudioDecoder({
output: frame => { outputChain = outputChain.then(() => schedule(frame)).catch(onError); },
error: onError,
});
decoder.configure(config);
​
async function waitForCapacity() {
while (decoder.decodeQueueSize >= 6 || queuedSeconds >= 0.8)
await new Promise(resolve => setTimeout(resolve, 16));
}
function decode(packet) {
const duration = packet.durationUs / 1e6;
decoder.decode(new EncodedAudioChunk({
type: "key", timestamp: packet.timestampUs, duration: packet.durationUs, data: packet.bytes,
}));
queuedSeconds += duration;
}
async function schedule(frame) {
try {
const buffer = context.createBuffer(
frame.numberOfChannels, frame.numberOfFrames, frame.sampleRate,
);
for (let channel = 0; channel < frame.numberOfChannels; channel++) {
const samples = new Float32Array(frame.numberOfFrames);
await frame.copyTo(samples, { planeIndex: channel, format: "f32-planar" });
buffer.copyToChannel(samples, channel);
}
if (mediaAnchorUs === null) { mediaAnchorUs = frame.timestamp; contextAnchor = context.currentTime + 0.1; }
const timestampStart = contextAnchor + (frame.timestamp - mediaAnchorUs) / 1e6;
const start = Math.max(timestampStart, nextStart, context.currentTime + 0.025);
const source = context.createBufferSource();
source.buffer = buffer; source.connect(context.destination);
sources.add(source);
source.onended = () => {
sources.delete(source);
queuedSeconds = Math.max(0, queuedSeconds - buffer.duration);
source.disconnect();
};
source.start(start);
nextStart = start + buffer.duration;
} finally { frame.close(); }
}
function stop() {
decoder.reset();
for (const source of sources) { source.onended = null; source.stop(); source.disconnect(); }
sources.clear();
queuedSeconds = 0;
mediaAnchorUs = null; contextAnchor = 0; nextStart = context.currentTime;
}
return { waitForCapacity, decode, stop };
}
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-501AI Evaluation and Reliability

Turn product intent and risk into representative evaluations release gates traces service targets and continuously improving regression evidence.

17 concepts~22h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next