Decode Once, Keep What Fits: a Byte-Budget LRU Cache for Web Audio Buffers, With Tests for In-Flight Loads, Pinned Clips and Failed Fetches
A page of soundboard buttons looks cheap. Every button is one short clip, and a short clip is a small file. Then you decode a few of them and the memory story changes, because the file on the network is not the thing the
A page of soundboard buttons looks cheap. Every button is one short clip, and a short clip is a small file. Then you decode a few of them and the memory story changes, because the file on the network is not the thing the browser keeps. A compressed clip that was a modest download becomes raw audio once decodeAudioData() is done with it: 32-bit floats, every channel, every frame.
This post builds a small cache around that fact. It decodes a clip the first time someone taps its button, keeps the result so the second tap is instant, forgets the least recently used clips when a byte budget is exceeded, and refuses to throw away a clip that is playing at that moment. The code is plain JavaScript, and the tests run in Node with fakes, so no browser or audio hardware is needed to check the logic.
Why not just decode everything up front
The obvious design is to fetch and decode every clip on page load so that every tap is instant. It works for six buttons. For a board with a long grid it means a lot of network traffic for sounds nobody will press, and a lot of memory holding them. On a phone with a tight memory limit, that is the kind of page the browser tabs out of the background first.
The opposite design, decoding on every tap, makes each tap wait for the network and the decoder. The first tap on a button has to pay that wait anyway. The second one should not.
A cache sits between the two. Its job is small:
- Return a decoded buffer for a clip id, loading it if needed.
- If two taps arrive while the first load is still running, do the work once.
- Keep a bounded amount of audio in memory, dropping the clips used longest ago.
- Never drop a buffer that a player is using right now.
- Not remember failures, so a bad connection does not poison a button.
Count the bytes that actually matter
The budget has to be in bytes of decoded audio, not in number of clips, because clips differ. A one-second mono clip and a ten-second stereo clip are both "one item", and one of them is twenty times larger in memory.
An AudioBuffer exposes length (frames), numberOfChannels and sampleRate. Web Audio stores samples as 32-bit floats, so the size is:
export function bufferBytes(buffer) {
return buffer.length * buffer.numberOfChannels * 4;
}
That is the PCM size. It ignores a little bookkeeping the browser adds, which is fine for a budget. Pick the budget by testing on a low-end phone rather than by trusting a number from a blog post, mine included.
The cache
Two small decisions shape the code. First, a JavaScript Map remembers insertion order, so "least recently used" can be the first key. To mark a clip as used, delete it and insert it again. No linked list is needed at this size.
Second, the cache does not call fetch() or decodeAudioData() itself. It receives fetchBytes and decode as arguments. In the page those are two short wrappers; in the tests they are fakes that return a pretend buffer with a chosen length.
// A small LRU cache for decoded audio, sized in bytes. Plain ES module, no dependencies.
// fetchBytes(id) -> Promise, decode(bytes) -> Promise.
// Both are passed in, so the logic runs in Node with fakes and in the browser with
// fetch() and audioContext.decodeAudioData().
/** Decoded PCM size in bytes: Web Audio buffers hold 32-bit floats per channel per frame. */
export function bufferBytes(buffer) {
return buffer.length * buffer.numberOfChannels * 4;
}
export function createBufferCache({ maxBytes, fetchBytes, decode }) {
if (!(maxBytes > 0)) throw new RangeError("maxBytes must be a positive number");
const entries = new Map(); // id -> { buffer, bytes }, oldest first (Map keeps insertion order)
const loading = new Map(); // id -> Promise, so two taps on one button share one load
const pinned = new Map(); // id -> how many players are using it right now
let total = 0;
function evict(keep) {
for (const [id, entry] of entries) {
if (total <= maxBytes) break;
if (id === keep || pinned.get(id) > 0) continue; // keep what just loaded and whatever is playing
entries.delete(id);
total -= entry.bytes;
}
}
async function load(id) {
const bytes = await fetchBytes(id);
const buffer = await decode(bytes);
const size = bufferBytes(buffer);
if (size <= maxBytes) {
entries.set(id, { buffer, bytes: size });
total += size;
evict(id);
}
return buffer; // an oversized clip still plays once, it just is not kept
}
return {
get(id) {
const hit = entries.get(id);
if (hit) {
entries.delete(id); // re-insert to mark it as the most recently used
entries.set(id, hit);
return Promise.resolve(hit.buffer);
}
if (!loading.has(id)) {
const p = load(id).finally(() => loading.delete(id)); // a failure is not cached
loading.set(id, p);
}
return loading.get(id);
},
peek(id) { return entries.has(id) ? entries.get(id).buffer : null; }, // no reordering
pin(id) { pinned.set(id, (pinned.get(id) || 0) + 1); },
unpin(id) {
const n = (pinned.get(id) || 0) - 1;
if (n > 0) pinned.set(id, n); else pinned.delete(id);
evict();
},
stats() { return { items: entries.size, bytes: total, maxBytes, loading: loading.size }; },
ids() { return [...entries.keys()]; },
clear() { entries.clear(); total = 0; }
};
}
A few details are worth reading twice.
The loading map. get() stores the promise for an in-flight load. A second tap on the same button gets the same promise, so there is one fetch and one decode. .finally() removes the entry whether the load worked or not, which is also why a failed fetch is never cached: the next tap simply tries again.
evict(keep). After a load, the new buffer is inserted and the cache walks from the oldest entry, dropping unpinned ones until it is back under budget. The keep argument protects the clip that just finished loading. Without it, a cache that is full of pinned clips would throw away the buffer it had just decoded, and the person who tapped would get audio that is not stored anywhere. With it, the cache may go briefly over budget while clips are playing, and settles when they finish.
Oversized clips. A clip bigger than the whole budget is returned but not stored. It still plays once. That is better than failing, and better than evicting everything else to make room for one monster file.
Pins. pin(id) counts players. A button that starts two overlapping plays of the same clip pins it twice, and it stays safe until both have called unpin(id). unpin runs evict() so memory comes back as soon as the last player is done.
Using it in the page
Here is the wiring for a button. It is deliberately boring.
const ctx = new AudioContext();
const cache = createBufferCache({
maxBytes: 24 * 1024 * 1024,
fetchBytes: async (id) => {
const res = await fetch(`/clips/${id}.mp3`);
if (!res.ok) throw new Error(`clip ${id}: HTTP ${res.status}`);
return res.arrayBuffer();
},
decode: (bytes) => ctx.decodeAudioData(bytes)
});
async function play(id) {
if (ctx.state === "suspended") await ctx.resume();
const buffer = await cache.get(id);
const source = ctx.createBufferSource();
source.buffer = buffer;
source.connect(ctx.destination);
cache.pin(id);
source.onended = () => cache.unpin(id);
source.start();
}
The 24 MB figure in that snippet is a placeholder for the sketch, not a recommendation. Check res.ok before decoding: without that line, an error page gets handed to the decoder and the failure message points at the decoder instead of the network.
One more habit that pays off is warming the cache from intent, not from a timer. When a person hovers a button or a touch starts, call cache.get(id) and ignore the result. By the time the tap completes, the clip may already be decoded. Because get() shares in-flight loads, the warm-up and the real tap do not double the work.
What the tests check
The tests use a fake AudioBuffer with just length and numberOfChannels, and a harness that records how many times fetchBytes and decode were called.
import test from "node:test";
import assert from "node:assert/strict";
import { createBufferCache, bufferBytes } from "./buffer-cache.mjs";
// A fake AudioBuffer: 1 channel, frames long, so it costs frames * 4 bytes.
const fake = (frames, channels = 1) => ({ length: frames, numberOfChannels: channels });
function harness(maxBytes, sizes) {
const calls = { fetch: [], decode: 0 };
const cache = createBufferCache({
maxBytes,
fetchBytes: async (id) => { calls.fetch.push(id); if (sizes[id] === "fail") throw new Error("network"); return id; },
decode: async (id) => { calls.decode++; return fake(sizes[id]); }
});
return { cache, calls };
}
test("bufferBytes counts 4 bytes per sample per channel", () => {
assert.equal(bufferBytes(fake(1000, 2)), 8000);
});
test("two taps while loading share one fetch and one decode", async () => {
const { cache, calls } = harness(10000, { a: 100 });
const [x, y] = await Promise.all([cache.get("a"), cache.get("a")]);
assert.equal(x, y);
assert.deepEqual(calls.fetch, ["a"]);
assert.equal(calls.decode, 1);
});
test("a cached clip is served without another fetch", async () => {
const { cache, calls } = harness(10000, { a: 100 });
await cache.get("a"); await cache.get("a");
assert.equal(calls.fetch.length, 1);
});
test("the least recently used clip goes first when the budget is exceeded", async () => {
const { cache: small } = harness(900, { a: 100, b: 100, c: 100 }); // room for two
await small.get("a"); await small.get("b");
await small.get("a"); // touch a: order is now b, a
await small.get("c"); // pushes out b
assert.deepEqual(small.ids(), ["a", "c"]);
});
test("a clip that is playing is pinned and survives eviction", async () => {
const { cache } = harness(900, { a: 100, b: 100, c: 100 }); // room for two
await cache.get("a"); cache.pin("a");
await cache.get("b"); await cache.get("c");
assert.ok(cache.peek("a")); // pinned, so b was dropped instead
assert.equal(cache.peek("b"), null);
cache.unpin("a");
assert.ok(cache.stats().bytes <= 900);
});
test("two players on one clip need two unpins", async () => {
const { cache } = harness(450, { a: 100, b: 100 }); // room for one
await cache.get("a"); cache.pin("a"); cache.pin("a");
await cache.get("b"); // over budget, but a is pinned and b just loaded
assert.deepEqual(cache.ids(), ["a", "b"]);
cache.unpin("a"); // one player left: a is still protected, b is not
assert.deepEqual(cache.ids(), ["a"]);
await cache.get("b");
cache.unpin("a"); // last player done: now the older clip can go
assert.deepEqual(cache.ids(), ["b"]);
});
test("a clip bigger than the whole budget plays but is not kept", async () => {
const { cache } = harness(300, { big: 1000, a: 50 });
const buf = await cache.get("big");
assert.equal(buf.length, 1000);
assert.equal(cache.stats().items, 0);
await cache.get("a");
assert.deepEqual(cache.ids(), ["a"]);
});
test("a failed load is not cached and can be retried", async () => {
const sizes = { a: "fail" };
const { cache, calls } = harness(1000, sizes);
await assert.rejects(cache.get("a"), /network/);
assert.equal(cache.stats().loading, 0);
sizes.a = 100;
assert.equal((await cache.get("a")).length, 100);
assert.equal(calls.fetch.length, 2);
});
test("peek does not change the order, get does", async () => {
const { cache } = harness(900, { a: 100, b: 100, c: 100 });
await cache.get("a"); await cache.get("b");
cache.peek("a");
await cache.get("c");
assert.deepEqual(cache.ids(), ["b", "c"]);
});
test("maxBytes must be positive", () => {
assert.throws(() => createBufferCache({ maxBytes: 0, fetchBytes() {}, decode() {} }), RangeError);
});
Run with node --test buffer-cache.test.mjs. Result:
รขลโ bufferBytes counts 4 bytes per sample per channel (0.991644ms)
รขลโ two taps while loading share one fetch and one decode (1.652483ms)
รขลโ a cached clip is served without another fetch (0.163405ms)
รขลโ the least recently used clip goes first when the budget is exceeded (0.192539ms)
รขลโ a clip that is playing is pinned and survives eviction (0.331759ms)
รขลโ two players on one clip need two unpins (0.211062ms)
รขลโ a clip bigger than the whole budget plays but is not kept (0.160022ms)
รขลโ a failed load is not cached and can be retried (0.477954ms)
รขลโ peek does not change the order, get does (0.2428ms)
รขลโ maxBytes must be positive (0.282271ms)
รขโยน tests 10
รขโยน suites 0
รขโยน pass 10
รขโยน fail 0
รขโยน cancelled 0
รขโยน skipped 0
รขโยน todo 0
รขโยน duration_ms 57.360153
Each test pins one decision:
-
In-flight sharing. Two simultaneous
get("a")calls return the same object and the fakes are called once. - Hits. A cached clip does not trigger a second fetch.
-
LRU order. Touching
amoves it to the back of the line, so loadingcremovesb, nota. - Pins. A pinned clip survives while an unpinned one is dropped instead, and two players need two unpins.
- Oversize. A clip larger than the budget plays but leaves the cache empty.
-
Failure. A rejected fetch leaves
loadingempty, and a retry works. -
peek. Looking without touching does not change the order, which is handy for a debug panel.
What the tests do not cover is the real decoder. decodeAudioData() can reject on a corrupt file or an unsupported format, and the cache passes that rejection through. Memory pressure is also outside what a Node test can show: the browser can still discard a tab regardless of how tidy your budget is.
Edge cases to think about next
-
Sample rate.
decodeAudioData()resamples to the context's rate, so the decoded size depends on the context. Create one context and reuse it. - Huge grids. If a board has hundreds of buttons, a fixed byte budget keeps memory flat however far someone scrolls.
-
Looping clips. A looping source stays pinned until it is stopped. Remember to call
unpinon stop, not only onended. -
Reduced data. If you want to be careful on metered connections, skip the hover warm-up when the
Save-Datahint is on.
If you want to see what a large grid of short clips looks like from the listener's side, the sound buttons guide on Meme Tap explains how a browser soundboard works for someone who just wants to tap and listen. The cache above is the part you do not see: a few dozen lines that make the second tap feel instant and keep a phone from running out of memory.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.