Most audio visualizer demos stop at "it moves on screen". The harder part is the last step: giving the user a video file they can post somewhere, with the sound in it, made entirely in the tab.
The browser has everything you need for that. canvas.captureStream() turns a canvas into a video track, an AudioContext can hand you an audio track, and MediaRecorder muxes both into one file. The part that bites is everything around it: which container the browser will actually record, what size the frame should be, how to map frequency data to bars, and what happens in a background tab.
I'll go through the pipeline, then pull out the pieces that don't need a browser so they can be tested in Node. Disclosure: I build Meme Tap, a free meme soundboard that has an in-browser visualizer exporter, and that is where this problem came from. Nothing below depends on it.
The pipeline in one picture
audio file ──decodeAudioData──▶ AudioBufferSourceNode ──▶ AnalyserNode ──▶ MediaStreamAudioDestinationNode ─┐ │ ├─▶ MediaStream ─▶ MediaRecorder ─▶ Blob getByteFrequencyData() ──▶ draw on <canvas> ─▶ captureStream() ─┘ Two streams, one recorder. The analyser feeds your drawing code, and the same audio goes to a MediaStreamAudioDestinationNode so the recorder hears it. The canvas side uses HTMLCanvasElement.captureStream().
One consequence is easy to miss: recording runs in real time. A 12-second clip takes 12 seconds to export. There is no "render faster than real time" with this approach, so plan the UI around a progress state and a Stop button.
Part 1: choose a container the browser can actually record
Don't hard-code video/webm. Browsers differ in what MediaRecorder accepts, and passing an unsupported mimeType throws. Ask first, with an ordered preference list:
export const CANDIDATE_TYPES = [ 'video/webm;codecs=vp9,opus', 'video/webm;codecs=vp8,opus', 'video/webm', 'video/mp4', ]; export function pickMimeType(isSupported, candidates = CANDIDATE_TYPES) { for (const type of candidates) { if (isSupported(type)) return type; } return ''; // let the browser choose } export function extensionFor(mimeType) { return /^video\/mp4/i.test(mimeType || '') ? 'mp4' : 'webm'; } Passing isSupported in, instead of calling MediaRecorder.isTypeSupported directly, is what makes this testable. In the browser you call pickMimeType((t) => MediaRecorder.isTypeSupported(t)); in a test you pass a fake:
test('Safari-like browser that only records mp4 gets mp4', () => { const type = pickMimeType((t) => t === 'video/mp4'); assert.equal(type, 'video/mp4'); assert.equal(extensionFor(type), 'mp4'); }); Use recorder.mimeType after construction for the final Blob type, not the string you asked for. The browser may have normalised it.
Part 2: fixed frame sizes
Social apps crop to a shape, so the exporter should offer shapes instead of free-form sizes. Three cover most uses:
export const FRAMES = { '16:9': { w: 1280, h: 720 }, '9:16': { w: 720, h: 1280 }, '1:1': { w: 720, h: 720 }, }; export function frameFor(aspect) { const frame = FRAMES[aspect]; if (!frame) throw new RangeError(`Unknown aspect "${aspect}". Use one of: ${Object.keys(FRAMES).join(', ')}`); return frame; } Landscape for desktop players, vertical for Shorts and Reels, square for feeds and chats. Those are the same three frames the Meme Tap audio visualizer uses. Set canvas.width and canvas.height to the frame size once and keep the preview and the export on the same canvas, so what the user sees is what gets recorded.
Part 3: frequency data to bars, on a log scale
AnalyserNode.getByteFrequencyData() fills a Uint8Array with values from 0 to 255, one per frequency bin, spaced linearly. If you split the array into equal chunks, the first few bars take all the bass and half your bars show frequencies almost nobody can hear. Hearing is closer to logarithmic, so bucket on a log scale:
export function logEdges(binCount, barCount, minBin = 1) { if (barCount < 1 || binCount < barCount + minBin) { throw new RangeError('Need at least barCount + minBin frequency bins'); } const edges = []; for (let i = 0; i <= barCount; i++) { edges.push(Math.round(minBin * Math.pow(binCount / minBin, i / barCount))); } edges[0] = minBin; edges[barCount] = binCount; // Low buckets can round to the same bin: force strictly increasing edges. for (let i = 1; i <= barCount; i++) edges[i] = Math.max(edges[i], edges[i - 1] + 1); for (let i = barCount - 1; i >= 0; i--) edges[i] = Math.min(edges[i], edges[i + 1] - 1); return edges; } export function barHeights(freq, barCount, maxHeight, minBin = 1) { const edges = logEdges(freq.length, barCount, minBin); const heights = new Array(barCount); for (let i = 0; i < barCount; i++) { let peak = 0; for (let b = edges[i]; b < edges[i + 1]; b++) peak = Math.max(peak, freq[b]); heights[i] = (peak / 255) * maxHeight; } return heights; } The rounding fix-up loops are the bug magnet here. With 32 bars over 1024 bins, the first several log buckets all round to the same one or two bins, which would give you empty buckets. The two passes guarantee every bar owns at least one bin and the last edge still lands on binCount.
Tests that catch the mistakes I'd expect to make:
test('logEdges are strictly increasing and cover the range', () => { for (const [bins, bars] of [[1024, 32], [1024, 64], [128, 48], [64, 60]]) { const e = logEdges(bins, bars); assert.equal(e.length, bars + 1); assert.equal(e[0], 1); assert.equal(e[bars], bins); for (let i = 1; i < e.length; i++) assert.ok(e[i] > e[i - 1]); } }); test('a single loud bass bin only lights the first bar', () => { const freq = new Uint8Array(1024); freq[1] = 255; const h = barHeights(freq, 16, 100); assert.equal(h[0], 100); assert.ok(h.slice(1).every((v) => v === 0)); }); test('a single loud treble bin only lights the last bar', () => { const freq = new Uint8Array(1024); freq[1000] = 128; const h = barHeights(freq, 16, 255); assert.equal(h[15], 128); assert.ok(h.slice(0, 15).every((v) => v === 0)); }); I'm using the peak of each bucket, not the average. Averages flatten short transients, and short transients are exactly what meme sounds are made of.
Part 4: the wiring (browser only)
This is the part I would not try to unit test. It is glue between browser objects, so treat it as something to check by hand.
export async function exportVisualizer({ file, aspect, draw, fps = 30 }) { const { w, h } = frameFor(aspect); const mimeType = pickMimeType((t) => MediaRecorder.isTypeSupported(t)); const ctx = new AudioContext(); await ctx.resume(); // call this from a click handler: contexts start suspended const buffer = await ctx.decodeAudioData(await file.arrayBuffer()); const src = ctx.createBufferSource(); src.buffer = buffer; const analyser = ctx.createAnalyser(); analyser.fftSize = 2048; const dest = ctx.createMediaStreamDestination(); src.connect(analyser); analyser.connect(dest); // do NOT connect to ctx.destination if you want a silent export const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; const g = canvas.getContext('2d'); const stream = new MediaStream([ ...canvas.captureStream(fps).getVideoTracks(), ...dest.stream.getAudioTracks(), ]); const recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined); const chunks = []; recorder.ondataavailable = (e) => e.data.size && chunks.push(e.data); const done = new Promise((resolve) => { recorder.onstop = () => { stream.getTracks().forEach((t) => t.stop()); ctx.close(); resolve({ blob: new Blob(chunks, { type: recorder.mimeType }), ext: extensionFor(recorder.mimeType) }); }; }); const bins = new Uint8Array(analyser.frequencyBinCount); let raf = 0; const tick = () => { analyser.getByteFrequencyData(bins); draw(g, w, h, bins); // your style: bars, waveform, circular raf = requestAnimationFrame(tick); }; src.onended = () => { cancelAnimationFrame(raf); recorder.stop(); }; recorder.start(); src.start(); tick(); return done; } A few things in there are deliberate:
- Stop on the source's
ended, not on a timer. The clip length decides the video length, and a timer drifts. - Stop the tracks in
onstop, after the recorder has flushed its last chunk, not before. -
ctx.resume()from a user gesture. Browsers keep anAudioContextsuspended until the user interacts with the page, so an export triggered from a click handler is fine and one triggered on page load is not. - Keep the tab visible while exporting. Browsers throttle or pause
requestAnimationFramein background tabs, so the picture can freeze while the audio carries on. Say so in the UI, and consider disabling the Export button until the tab is in front.
Two compatibility notes. Safari and Chromium don't record the same containers, which is why Part 1 asks instead of assuming. And WebM files written by MediaRecorder are written as a stream, so some players show no duration or won't seek in them. Check the players your users actually use before you promise "works everywhere"; if that matters, re-mux the file or offer an MP4 path where the browser supports it.
Limits worth stating in the UI
Real-time recording and in-memory chunks mean long files cost time and memory. Cap the input size and say what the cap is. Meme Tap's visualizer, for example, asks for files under 40 MB and accepts MP3, WAV or OGG, and the page says the file stays on the device. Whatever limits you pick, show them before the user waits through an export.
Run the tests
node --test # tests 14, pass 14, fail 0 The functions are plain ES modules with no dependencies, so node --test is all you need.
What I'd do next
- Add a second
drawstyle that uses the time-domain data (getByteTimeDomainData) for a waveform line. - Smooth bar heights between frames (a simple attack/decay) so quiet passages don't flicker.
- If you want to try the finished version of this idea rather than build it, the Meme Tap audio visualizer is free and runs in the tab.
If you've shipped something like this, I'd like to hear which browser gave you the most trouble.
