Audio-Reactive From Zero · Episode 06
Audio-Reactive Particles
Audio-Reactive Particles is Episode 06 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 .
This is the one you screen-record and post. A storm of thousands of glowing particles, drifting in the dark — until the music hits, and the whole field inhales. The kick punches a radial spray of sparks out of the center. The bass swells every particle fat and bright. The hi-hats flick the color toward electric cyan. The mid-range melody nudges the drift left and right. It is the creative-coding screensaver you cannot stop watching, and it is reacting to sound in real time.
And it is alive the instant the page loads — no click required.
A synthetic ~128 BPM track drives everything from the first frame, so you see the
storm dance before you ever grant microphone access. Hit 🔊 enable sound
to swap in a real audio graph (a built-in synth, your mic, or a file) and feed the
same particle system from live FFT data. The particles never know the difference:
they read one spectrum array and one waveform array, and
that is the entire contract.
What you're looking at
One particle system, six progressively wired stages, and two little arrays doing all the talking. Every particle is a tiny struct — position, velocity, life, size, hue — living inside a pre-allocated pool that never grows or shrinks. Each frame we read the audio, decide how to push the particles, integrate their motion by the real frame time, and draw them with additive glow over a translucent fade so they leave comet trails.
The spectrum array (256 bins, bass on the left, treble on the right)
and the waveform array (256 time-domain samples) are the only inputs. The
demo fills them from synthAudio() by default — a fake but musical track —
and from a live AnalyserNode once you enable sound. Watch the
fps readout: this holds 60fps with thousands of particles because we
never allocate during the animation loop and never let the pool leak.
Step the stage selector from 1 to 6 to add one mapping at a time. Drag
on the canvas to hand-inject particles wherever you point — useful for feeling the
physics. The whole thing is ~300 lines of plain canvas 2D and zero dependencies.
Stage 1 — A calm particle field
No audio mapping at all. The pool emits a gentle trickle of particles from the center; they drift outward with a touch of curl, fade as their life runs down, and get recycled. This is the substrate — the same physics that every later stage decorates. It already looks like a screensaver, but it is deaf. Notice it is moving on first paint regardless: the motion here is pure time, not sound.
Stage 2 — Bass → size and brightness
The first audio wire. We compute a single bass scalar by averaging
the lowest ~8% of the spectrum, then feed it into every particle's draw radius and
alpha. On the synthetic track, that band is dominated by the kick (see
synthAudio), so the whole field swells and dims with the beat
like it is breathing. One number, mapped to size, and the field suddenly has a pulse.
Stage 3 — Beat → burst
Now it gets percussive. We run detectBeat() on the bass band every
frame; when it fires, we emit a radial spray — a fixed-count burst of
particles launched outward in all directions from the center. The refractory window
guarantees one kick equals one burst, and we cap the burst size so a loud passage
cannot flood the pool. This is the single most satisfying line in the episode: the
storm explodes on the downbeat.
Stage 4 — Treble → hue
Color comes alive. We average the top third of the spectrum into a treble scalar and use it to push the hue of newly-emitted particles. Quiet highs sit in the palette's cool base; a burst of hi-hats or cymbals shoves the sparkles toward the hot end. Because each particle locks its hue at birth, you get layered color — old calm particles in one tone, fresh sparkly ones in another, drifting together.
Stage 5 — Spectrum → radial force field
Here the shape of the sound steers the motion. We treat the particle's angle from center as an index into the spectrum: a particle sitting at 3 o'clock reads a bass-ish bin, one at 9 o'clock reads treble. Whatever magnitude it finds becomes an outward push. Loud frequencies blow particles outward along their matching direction, so the storm literally takes the silhouette of the spectrum — a living, rotating equalizer made of light.
Stage 6 — Full storm
Everything at once: idle drift, bass swell, beat bursts, treble hue, spectrum force
— plus trails and additive glow and your chosen palette. This is the shareable result.
Crank reactivity up for a seizure of light, or down for something you
could actually use as a wallpaper. Switch palettes. Enable your mic and play a song.
This stage is the promise of the whole episode delivered.
How the code works
Four ideas carry the whole demo: a pool you never reallocate, a beat that triggers a capped burst, audio bands that map to size/hue/force, and an additive-glow draw with trails. We'll take them in order.
The pre-allocated particle pool (no per-frame allocation)
The number-one way particle systems die is garbage. If you
new a particle every frame and let dead ones get collected, the GC will
eventually stutter your 60fps into chop. The fix is a pool: allocate
a fixed array of particle objects once, mark dead ones with
life <= 0, and recycle them in place. Memory is flat forever.
// Allocate ONCE. Every particle object is reused forever.
const MAX = 6000;
const pool = [];
for (let i = 0; i < MAX; i++) {
pool.push({ x:0, y:0, vx:0, vy:0, life:0, max:1, size:1, hue:0 });
}
let cursor = 0; // round-robin write head
// "Spawn" = grab the next slot and overwrite it. No allocation, ever.
function spawn(x, y, vx, vy, life, size, hue) {
const p = pool[cursor];
cursor = (cursor + 1) % activeCount; // wrap within the live cap
p.x = x; p.y = y; p.vx = vx; p.vy = vy;
p.life = life; p.max = life; p.size = size; p.hue = hue;
}
The cursor wraps at activeCount (driven by the slider), so
raising the slider grows the working set and lowering it shrinks it — but the backing
array is always MAX long. Spawning past capacity simply overwrites the
oldest particle, which is exactly the behavior you want: a hard ceiling that can never
leak. In the update loop we only touch the first activeCount slots.
detectBeat → emit a burst
Beat detection is the same running-average trick from the series brief: square the bass bins into an energy number, keep a short history, and call it a beat when the current energy spikes well above the recent average. The one addition is a refractory window so a single kick can't register as three beats on consecutive frames.
let energyHist = [], lastBeat = 0;
function detectBeat(spectrum, sensitivity = 1.3) {
let e = 0; const lim = Math.floor(spectrum.length * 0.12); // bass band
for (let i = 0; i < lim; i++) e += spectrum[i] * spectrum[i];
e /= lim;
energyHist.push(e); if (energyHist.length > 43) energyHist.shift(); // ~0.7s @60fps
const avg = energyHist.reduce((a, b) => a + b, 0) / energyHist.length;
return e > avg * sensitivity && e > 1000; // threshold + a floor
}
// In the frame: one kick → one capped radial spray.
const now = performance.now();
if (detectBeat(spectrum) && now - lastBeat > 120) { // 120ms refractory
lastBeat = now;
const burst = Math.min(90, 40 + bass * 60); // CAP so we never flood
for (let i = 0; i < burst; i++) {
const a = Math.random() * Math.PI * 2; // spray in all directions
const sp = 120 + Math.random() * 260; // px/sec outward
spawn(cx, cy, Math.cos(a)*sp, Math.sin(a)*sp, 0.8, 3, hue);
}
}
The Math.min(90, …) is doing real work: without that cap, a sustained
loud bassline fires on many frames and each fires dozens of particles, and you blow
your whole pool in a second of music. Cap the per-beat emission and the storm stays a
storm instead of a white-out.
Bands and spectrum → size, hue, and force
Three reductions of the spectrum drive three different particle properties. Bass and
treble are simple band averages; the radial force is per-particle, reading the bin that
matches each particle's angle. A single reactivity multiplier scales how
hard every mapping bites.
// Collapse bands to scalars in 0..1 once per frame.
function band(spectrum, lo, hi) { // lo,hi as fractions 0..1
let s = 0, a = (spectrum.length*lo)|0, b = (spectrum.length*hi)|0;
for (let i = a; i < b; i++) s += spectrum[i];
return s / ((b - a) * 255); // 0..1
}
const bass = band(spectrum, 0, 0.08); // the kick lives here
const treble = band(spectrum, 0.6, 1); // hats / sparkle
const hue = baseHue + treble * 140 * react; // highs push the color hot
// Per particle: size by bass, push by the matching spectrum bin.
const drawR = p.size * (1 + bass * 3 * react); // swell with the bass
const ang = Math.atan2(p.y - cy, p.x - cx); // where it sits
const bin = ((ang + Math.PI) / (Math.PI*2) * spectrum.length) | 0;
const push = spectrum[bin] / 255 * 340 * react; // outward force, px/sec²
p.vx += Math.cos(ang) * push * dt;
p.vy += Math.sin(ang) * push * dt;
Mids (the 0.08..0.6 band) drive a gentle horizontal drift in the full
demo — the melodic sway. The key discipline: every audio value is normalized to
0..1 and then scaled by react, so one slider takes you from
"subtle ambient" to "full rave" without touching the math.
Additive glow + trails
The look is 90% in the compositing. Two tricks: instead of clearing the canvas to
black each frame, paint a translucent black rectangle over it so old
frames fade out gradually — that is the trail. Then draw every particle with
globalCompositeOperation = 'lighter' so overlapping particles
add their light and the dense center blooms.
// Trails: fade the previous frame instead of clearing it.
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(6, 8, 16, ' + (1 - trail) + ')'; // trail 0..0.92
ctx.fillRect(0, 0, W, H);
// Glow: additive blending makes overlaps bloom.
ctx.globalCompositeOperation = 'lighter';
for (let i = 0; i < activeCount; i++) {
const p = pool[i];
if (p.life <= 0) continue;
const a = (p.life / p.max) * alpha; // fade as life runs out
const g = ctx.createRadialGradient(p.x, p.y, 0, p.x, p.y, drawR);
g.addColorStop(0, 'hsla(' + p.hue + ',100%,65%,' + a + ')');
g.addColorStop(1, 'hsla(' + p.hue + ',100%,55%,0)'); // soft edge
ctx.fillStyle = g;
ctx.beginPath(); ctx.arc(p.x, p.y, drawR, 0, Math.PI*2); ctx.fill();
}
The radial gradient per particle gives each one a soft, glowing falloff instead of a
hard disc — the difference between "confetti" and "embers." With 'lighter'
the bright core of the storm naturally clips to white where particles pile up, which is
exactly the bloom you want on a beat. Setting trail back to 1 (full clear
each frame) kills the comet tails for a cleaner, more pointillist look — both are valid;
Stage 6 leans into trails.
Common pitfalls
- Particle leaks. The instant you
push()new particles into a growing array and rely on the GC to clean dead ones, you have a leak and a frame-time cliff. Cap and recycle: fixed pool, round-robin cursor, dead particles overwritten in place. Memory must be flat for the whole session. - Beat-burst flooding.
detectBeatcan return true on several consecutive frames of one kick, and a sustained loud passage fires every frame. Without a refractory window and a per-beat emission cap, one bassline empties your pool and the screen goes solid white. Cap both. - Over-reactivity. The temptation is to map everything to maximum.
A storm that's pinned at full-tilt reads as noise; the eye can't find the beat. Keep
idle motion calm so the bursts pop against it — subtle reads as more musical
than seizure. That's what the
reactivityslider is for: ship the default low. - Trails vs. clear, gotcha. Translucent-fade trails never fully
reach black — faint ghosts linger and, with additive blending, slowly accumulate into
a grey haze. If your background creeps lighter over time, lower the trail amount (make
the fade more opaque) or periodically hard-clear. Pure
clearRectgives crisp frames but no comet tails. Pick per look. - Frame-rate-dependent motion. Multiply every velocity and force by
dt(seconds since last frame), never by a constant per frame. Skip this and your storm moves twice as fast on a 120Hz display and crawls when the tab is busy. Clampdtto a sane max (~0.05s) so a stutter doesn't teleport everything.
Exercises
- Emit along the waveform shape. Instead of spawning bursts from a
single point, walk the
waveformarray and spawn a particle atx = i/N * W,y = center + (waveform[i]-128) * scale. Now the emitter is the oscilloscope, and the storm peels off the vibrating string. Spawn sparsely (every 4th sample) to stay within the pool. - Gravity toward the loudest frequency. Each frame, find
argmax(spectrum)and convert that bin index to an angle. Add a small acceleration pulling every particle toward that direction. The whole storm will lean toward whatever frequency is dominant — bass on the downbeat, treble on a cymbal crash. A musical attractor. - A second emitter for snares. Run a second
detectBeattuned to the mid band (say0.15..0.35of the spectrum, lower sensitivity) and give its bursts a different palette offset and a flatter, wider spray. Now kicks and snares each have their own visual signature, and the storm reads the full groove, not just the four-on-the-floor.
What's next
Episode 07 — The Spectrogram Waterfall and the Radial "Audio Sun." We stop spraying particles and start painting time: a scrolling spectrogram that turns the last few seconds of sound into a heat-map you can read like sheet music, and a radial bloom — bins fanned around a circle — that pulses like a star going supernova on every beat. Same two arrays, a completely different gorgeous. If you want to push this particle storm to the GPU and run a million of them, the shaders and three.js series are the natural next hop.