Audio-Reactive From Zero · Episode 08
The Music Visualizer
The Music Visualizer is Episode 08 of Audio-Reactive From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Seven episodes ago we had two arrays of bytes. Now we close the season by spending them all at once. This is the capstone: a single, fullscreen-able music visualizer that reacts on every axis — a bass-warmed nebula behind a circular EQ, a core that punches on the beat, particles that burst with the kick and drift with the mids, and an oscilloscope ring tying the whole thing into one cohesive palette. Drop in a track, or hit your mic, and you've got a music video.
Everything you built this season shows up here, layered in order, drawn sixty times a second from one analyser. The demo below is already running on a synthetic track — no clicks required — so you can study the layers right now. Then press 🔊 enable sound, load an MP3, hit ⛶ fullscreen, and walk away with something you'd actually put behind a real track.
What you're looking at
One canvas, six layers, painted back-to-front every frame in a fixed order: background first so everything else sits on top of it, the oscilloscope ring last so it reads as the topmost outline. Each stage in the dropdown switches on one more layer, so you can see exactly what each contributes. Stage 6 is the finished visualizer — the thing this whole season was building toward.
The other controls shape the piece without changing the code path. scene
swaps the background's character (a soft nebula, a rushing tunnel, a roiling solar
flare). intensity scales how hard everything reacts — turn it up for a
festival, down for a lo-fi loop. palette recolors every layer at once from
one shared gradient, which is the trick that makes a pile of effects look like a single
designed thing rather than a demo reel. And 🔊 enable sound with its
synth / mic / file choice swaps the synthetic feed for real audio — the
only moment an AudioContext is ever touched.
Stage 1 — Background wash
We start with the room the music lives in: a full-frame radial gradient whose warmth and brightness ride the bass. On a kick the center blooms hot; between kicks it cools and dims. There are no bars or particles yet — just a breathing field of color. It looks like almost nothing on its own, and that's the point: it's the foundation every other layer is composited onto. A good visualizer is mostly background you don't consciously notice.
Stage 2 — + Radial spectrum
Now the EQ, bent into a circle. We take the lower two-thirds of the
spectrum and draw it as bars radiating out from the center — bass at the
top, sweeping clockwise through mids and treble and mirrored back, so the ring is
symmetric and never has an ugly seam. This is the same frequency-bars idea from Episode
02, just mapped to angle instead of x. Suddenly the wash has a face: a pulsing
circular equalizer that spells out the song's shape.
Stage 3 — + Beat core
A central form that exists to hit. It's a soft, glowing disc sized
by overall energy, but on every detected beat it gets a sharp punch of scale and
brightness that decays over a few frames. This is detectBeat from Episode
03 driving a single visual accent. The core is what makes the visualizer feel
locked to the track — your eye catches the punch and your brain says "yes, that
was the kick." Without it, busy visualizers read as random shimmer.
Stage 4 — + Particles
The Episode 06 particle system, folded in. A sane number of particles (a few hundred) drift outward, their base speed pushed by the mids and their shimmer by the treble. On a beat we burst a ring of fresh particles from the core, so the kick visibly throws sparks. Crucially this is one pooled array we recycle — we never allocate inside the loop and we cap the count, because the whole danger of a "throw everything in" finale is death by a thousand layers. Particles are where that bites first.
Stage 5 — + Waveform ring
The last layer and the one that ties it together: an oscilloscope drawn as a closed
ring around the core, plotting the waveform (the time-domain signal) as a
wobble in the ring's radius. Where the radial spectrum shows how much of each
frequency, the waveform ring shows the raw wave — the actual shape of the
sound, rendered as a living circle. This stage also leans hardest on the shared
palette: the ring, the bars, the core, and the glow all draw from the
same four-stop gradient, so the frame reads as one coherent image.
Stage 6 — The full visualizer
Everything at once, plus the two things that make it a finished piece rather than a teaching diagram: a ⛶ fullscreen button (the Fullscreen API on the demo element) and real track / mic input. Load a song, press fullscreen, dim the lights. This is the deliverable — the screen you put behind a track. Everything below is how it's wired.
How the code works
The architecture is the same as every episode this season, just with more consumers
of the same two arrays. readAudio fills spectrum and
waveform once per frame — from the synthetic generator by default, or from
the live analyser after you enable sound — and then derives the handful of scalars every
layer reads: three frequency bands, a beat flag, and an overall
energy. Compute these once; never let a layer re-scan the
spectrum.
// (a) Read audio + derive bands/beat/energy ONCE per frame.
const N = 256;
const spectrum = new Uint8Array(N), waveform = new Uint8Array(N);
const bands = { bass: 0, mid: 0, treble: 0 };
let energy = 0, beat = false;
function bandAvg(a, lo, hi) { // mean of a spectrum slice, 0..1
let s = 0; for (let i = lo; i < hi; i++) s += a[i];
return s / ((hi - lo) * 255);
}
function readAudio(t) {
if (usingReal && analyser) { // live source (synth/mic/file)
analyser.getByteFrequencyData(srcFreq);
analyser.getByteTimeDomainData(srcTime);
resampleInto(srcFreq, spectrum);
resampleInto(srcTime, waveform);
} else {
synthAudio(t, spectrum, waveform); // alive with no AudioContext
}
bands.bass = bandAvg(spectrum, 0, 10); // ~0–8% : the kick
bands.mid = bandAvg(spectrum, 10, 70); // melody / vocals
bands.treble = bandAvg(spectrum, 70, 180); // cymbals / air
energy = (bands.bass * 1.4 + bands.mid + bands.treble * 0.6) / 3;
beat = detectBeat(spectrum, 1.32); // Ep03 helper, copied below
}
The render is a sequence of layer functions called in a strict order. Order is
the whole ballgame. Background must paint first (it's the canvas clear), the ring
must paint last (it's the topmost outline), and the beat core sits between the bars and
the particles so sparks read as flying off it. The stage value is
just how many layers we let run:
// (b) The layered draw — back-to-front, in order. `s` = active stage (0..5).
function draw(t) {
const s = stage, k = intensity, pal = PALETTES[paletteName];
drawBackground(t, k, pal); // 1 · always — it's the clear
if (s >= 1) drawRadialSpectrum(t, k, pal); // 2 · circular EQ
if (s >= 2) drawBeatCore(t, k, pal); // 3 · punches on beat
if (s >= 3) { updateParticles(t, k); drawParticles(pal); } // 4 · burst + drift
if (s >= 4) drawWaveformRing(t, k, pal); // 5 · oscilloscope ring
}
// Background: a band-driven radial wash. Bass = warmth + brightness.
function drawBackground(t, k, pal) {
const warm = bands.bass * k;
const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, R * (1.1 + warm));
g.addColorStop(0, mix(pal[0], pal[1], 0.3 + warm)); // hot center on the kick
g.addColorStop(1, '#05060a');
ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
}
The source switch is the one piece of real Web Audio, and it only ever runs from a
click. enableSound(mode) lazily creates and resume()s the
AudioContext, builds the analyser, and connects the chosen node. The
file path is the subtle one: an <audio> element wants
createMediaElementSource, and you must connect the analyser on to
destination or the file plays silently (the analyser taps the
signal but doesn't pass it through by itself). The mic deliberately does not
reach the destination, or you'd get a feedback howl.
// (c) The source switch — synth / mic / file. Gesture-gated, try/catch fallback.
async function enableSound(mode) {
try {
cleanupSource(); // stop any previous node first
audioCtx = audioCtx || new (window.AudioContext || window.webkitAudioContext)();
await audioCtx.resume(); // REQUIRES this user gesture
analyser = audioCtx.createAnalyser();
analyser.fftSize = 1024;
analyser.smoothingTimeConstant = 0.82;
srcFreq = new Uint8Array(analyser.frequencyBinCount);
srcTime = new Uint8Array(analyser.frequencyBinCount);
if (mode === 'mic') {
micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
node = audioCtx.createMediaStreamSource(micStream);
node.connect(analyser); // mic → analyser ONLY (no feedback)
} else if (mode === 'file') {
mediaEl = new Audio(); mediaEl.src = fileURL; mediaEl.loop = true;
node = audioCtx.createMediaElementSource(mediaEl);
node.connect(analyser); analyser.connect(audioCtx.destination); // → speakers!
await mediaEl.play();
} else {
node = buildSynth(audioCtx); // looping synth so there's sound
node.connect(analyser); analyser.connect(audioCtx.destination);
}
usingReal = true; setStatus('live · ' + mode);
} catch (e) {
usingReal = false; setStatus('audio unavailable — staying synthetic (' + e.name + ')');
}
}
Finally, the bit that turns it from a widget into a piece: fullscreen.
The Fullscreen API requests on whatever element you hand it — we pass the
.demo div, so the canvas, controls, and badge all go fullscreen together.
It must be called from a user gesture (same rule as audio), and it returns a Promise you
should catch in case the browser refuses. We toggle, and our resize handler
(already wired) re-fits the canvas to the new size on the next frame:
// (d) Fullscreen API — request on the demo element, from a click, with a fallback.
fullBtn.addEventListener('click', () => {
const el = demo; // the whole .demo block
if (!document.fullscreenElement) {
(el.requestFullscreen || el.webkitRequestFullscreen).call(el)
?.catch(() => setStatus('fullscreen blocked by browser'));
} else {
document.exitFullscreen?.();
}
});
// re-fit the canvas whenever fullscreen enters/exits
document.addEventListener('fullscreenchange', resize);
And the beat detector, copied verbatim from Episode 03 — a running-average threshold plus a refractory window so one kick counts as exactly one beat:
// detectBeat — energy in the bass band vs a ~0.7s running average + a refractory gate.
let energyHist = [], lastBeatT = 0;
function detectBeat(spec, sensitivity = 1.3) {
let e = 0; const lim = Math.floor(spec.length * 0.12);
for (let i = 0; i < lim; i++) e += spec[i] * spec[i];
e /= lim;
energyHist.push(e); if (energyHist.length > 43) energyHist.shift();
const avg = energyHist.reduce((a, b) => a + b, 0) / energyHist.length;
const now = performance.now();
if (e > avg * sensitivity && e > 1000 && now - lastBeatT > 120) {
lastBeatT = now; return true; // refractory: ignore beats within 120ms
}
return false;
}
Common pitfalls
- Silent until you click. Browsers start every
AudioContextsuspended; it can only be created/resumed inside a user gesture. That's exactly why the visuals run on a synthetic feed first and the real graph is built only in the🔊 enable soundhandler. Never touchAudioContextat load. - Layer order looks wrong. If the background paints over your bars,
or the ring hides behind particles, you drew them in the wrong sequence. Background is
the clear (first); ring is the topmost outline (last). When in doubt, re-read the
draw()order — it's the contract. - It chugs / fps tanks. A finale is where "throw everything in"
bites. Use one analyser, derive bands/beat once per frame, cap particles to a
few hundred, recycle a pooled array instead of allocating in the loop, and avoid
per-frame
createRadialGradientwith hundreds of stops. Sane counts beat clever effects. - The loaded file plays but you hear nothing. For a file you need
createMediaElementSourceandanalyser.connect(destination). The analyser only taps the signal; it doesn't forward it to the speakers on its own. (The mic is the opposite — never connect it todestinationor it howls.) - Switching sources leaks or double-plays. Tear down the old source
before building a new one: stop the synth oscillators,
pause()and clear the<audio>, stop the mic'sMediaStreamTracks, and disconnect. Otherwise the previous track keeps feeding the analyser. - Fullscreen is blank or wrong-sized. Request fullscreen on the
.demoelement (not the canvas alone), call it from a click, and re-run your resize/DPR fit onfullscreenchangeso the backing store matches the new dimensions.
Exercises
- Record the visualizer.
canvas.captureStream(60)hands you aMediaStreamof the canvas; feed it to aMediaRecorderand you can save a.webmof your visualizer to disk. Mix in the audio track (audioCtx.createMediaStreamDestination()) and you've rendered an actual music video — no screen-capture software. Add a● recbutton next to fullscreen. - Auto-cycle presets on the beat. Keep a beat counter in
readAudio; every N beats (say 16) advance thesceneorpaletteto the next option. The visualizer now re-themes itself in time with the music — set-and-forget for a long track. - Beat-synced camera shake. On each beat, add a small random
offset to a
shakevector and decay it toward zero every frame; apply it withctx.translate(shake.x, shake.y)before drawing (and reset the transform after). A subtle kick-driven shake makes the whole frame feel like it's being hit. Keep the amplitude small — a few pixels — or it reads as a bug.
What's next
That's a wrap on Season 1 — The Spectrum. You went from "what even is an FFT" to a finished, fullscreen, track-reactive music visualizer, and you wrote every line of the rendering yourself against two little byte arrays. Be loud about it: record a clip, drop it behind a track, ship it.
Season 1 was about reading sound. Season 2 — Synthesis & Advanced is about making it and pushing the reactivity further: build instruments with oscillators and envelopes, sequence a real drum machine in the Web Audio clock, route audio through effect graphs, and finally hand the spectrum to the GPU for shader-reactive visuals that laugh at particle counts. Everything you learned about the data model carries straight over — now you'll be on both ends of the wire.
For more reactive-visual playgrounds in the meantime: the Shaders From Zero series is where you'd push this visualizer onto the GPU, and Three.js From Zero is where it goes 3D.