Audio-Reactive From Zero · Episode 01

Sound Is Just Numbers

Sound Is Just Numbers is Episode 01 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 .

Episode 01 · Audio-Reactive From Zero

Right now, somewhere, a song is playing — and to the machine it's playing on, that song is not music. It's an array. A few hundred small whole numbers, between 0 and 255, overwritten sixty times every second. The bass is one number getting big. A cymbal is a cluster of numbers near the end of the array shimmering. The whole emotional arc of a track — the drop, the breakdown, the final chorus — is, to your code, a list of integers changing shape. Every audio visualizer you've ever seen is just someone drawing that list.

This series teaches you to read and draw that list, from absolute zero, with no libraries — only the browser's built-in Web Audio API and a 2D canvas. And here's the trick that makes the whole series learnable: you don't need any audio to start. The demo below is already alive, already pulsing to a fake song we generate with a little math, so you can see the numbers before you ever grant a microphone. Then, with one click, you swap in your real mic or a track, and the exact same drawing code lights up to the real thing. Let's look at the numbers.

0 fps
hover a bar in stage 6 to read its value
synthetic — no audio needed
Web Audio · synthetic
The first 16 spectrum numbers, live. These update every single frame.

What you're looking at

That box is the entire series in miniature. There are two arrays behind it — call them spectrum and waveform — and every stage is just a different way of drawing the same two arrays. By default they're filled by a fake-song generator, so it runs forever with nothing plugged in. The 🔊 enable sound button trades that fake source for a real one (a built-in synth, your mic, or a file) without changing a single line of drawing code. The badge at the bottom-left tells you which you're on: synthetic or live.

Step through the stage dropdown top to bottom. Each one peels back a layer: first the raw numbers as text, then those numbers as bars, then the waveform, then both at once, then real sound, and finally a hover-to-inspect view that proves there's nothing up our sleeve — it really is just an array.

Stage 1 — The raw array

This is the most honest view in the entire series: the actual numbers. The top row prints spectrum[0] through spectrum[15] as live text, and below them a handful of bars for the same values. Watch index 0 and 1 — they spike hard on every kick, because the start of the array is the bass. The numbers never stop moving because we refill the array every frame, sixty times a second. Burn this in: a frequency spectrum is literally spectrum[i], an integer from 0 to 255, where low i is low pitch and high i is high pitch.

Stage 2 — Spectrum bars

Now draw all of them. Each array slot becomes one vertical bar, its height set by the value 0–255. This is the classic equalizer look, and it falls out of three lines of canvas code: loop over the array, map each value to a pixel height, fill a rectangle. The bars slider changes how many bins we draw by averaging the underlying array down to N — your visual resolution and the data's resolution are two different things, a point we'll hammer in the pitfalls. Watch the shape: a fat, pumping left side (bass), a lively middle (melody), and a fine sparkle on the right (treble).

Stage 3 — Waveform

The second array is a completely different view of the same sound. Where the spectrum answers "how much of each pitch?", the waveform answers "where is the speaker cone right now?" — it's the raw pressure wave over time, the squiggle you see in any audio editor. It's centered on 128: silence is a flat line through the middle, and loud sound swings far above and below. We draw it as a single connected stroke, one array slot per horizontal step. Notice it's jagged and fast where the spectrum is smooth — same instant, two lenses.

Stage 4 — Both

Put them on top of each other and you can see they're describing the same moment from two angles: the bars rise on a beat at the same time the waveform swells. This pairing — frequency bars plus a time-domain trace — is the skeleton under a huge fraction of music visualizers. Everything else in this series is decoration on these two arrays: color them, smooth them, bend them into circles, push them onto a GPU. The data never changes.

Stage 5 — Enable sound

Everything so far ran on a fake song. Click 🔊 enable sound and, on that click (browsers require a user gesture — more on that below), we spin up a real AudioContext, attach an AnalyserNode, and point a source at it. Pick synth for a built-in looping tune you can hear, mic to visualize your own voice or whatever's in the room, or file to load a track off your disk. The badge flips to live and the status line tells you which mode. Crucially, the bars and waveform you're already watching don't know or care — they read the same two arrays, now filled by the analyser instead of our math.

Stage 6 — It's just an array

The closing argument. Hover any bar and a readout shows its exact index and value, like inspecting one cell of a spreadsheet — because that's all it is. There's no audio magic here, no DSP wizardry you can't see. Once you accept that a song is a Uint8Array that updates 60×/second, the whole field opens up: anything you can do to numbers, you can do to music. Scale a circle by the bass. Spawn a particle on a beat. Drive a shader uniform with the treble. That's Episodes 02 through 08 — and they're all just more interesting things to do with these same numbers.

How the code works

The architecture is deliberately tiny. Allocate the two arrays once, fill them every frame from whatever source is active, and draw. The data flow is one line:

source (synth math ·or· AnalyserNode) │ fills, in place, every frame ▼ spectrum[] + waveform[] ← the only state the visuals ever read │ ▼ draw bars / trace / text on the canvas

1 · The synthetic source (alive with no audio)

Before any microphone exists, this function fabricates a musical-looking spectrum and waveform from time t alone. It fakes a ~128 BPM track: a sharp bass kick on every beat, a melodic wobble in the mids, sparkle in the treble, and a slow overall swell. It writes straight into the shared arrays, so the rest of the code can't tell it apart from real audio:

const N = 256;
const spectrum = new Uint8Array(N), waveform = new Uint8Array(N);

function synthAudio(t, spectrum, waveform) {
  const N = spectrum.length;
  const bpm = 128, beatPhase = (t * bpm / 60) % 1;
  const kick = Math.pow(1 - beatPhase, 6);           // sharp decay each beat
  const swell = 0.5 + 0.5 * Math.sin(t * 0.5);
  for (let i = 0; i < N; i++) {
    const f = i / N;                                  // 0=bass .. 1=treble
    let a;
    if      (f < 0.08) a = 210 * kick + 70 * swell;                         // bass: the kick
    else if (f < 0.45) a = 120 + 80 * Math.sin(t * 3 + i * 0.25) * (1 - f); // mids: melody
    else               a = 90 * (1 - f) * (0.6 + 0.4 * Math.sin(t * 9 + i)) + 40 * kick;
    a *= (0.65 + 0.5 * swell);
    spectrum[i] = Math.max(0, Math.min(255, a * Math.exp(-f * 1.1)));     // natural roll-off
  }
  for (let i = 0; i < N; i++) {
    const x = i / N;
    const s = Math.sin(x * Math.PI * 8 + t * 6) * 0.5 + 0.4 * Math.sin(x * Math.PI * 22 + t * 11);
    waveform[i] = Math.max(0, Math.min(255, 128 + 95 * s * (0.4 + 0.6 * kick)));
  }
}

2 · Enable sound — the real graph, gesture-gated

The real Web Audio path. Three objects matter: the AudioContext (the audio engine), the AnalyserNode (the thing that hands you arrays), and a source feeding the analyser. The non-negotiable rule: you may only create and resume() the context inside a real user gesture, which is why this lives in a button click. Everything is wrapped in try/catch so any failure falls straight back to the synthetic source instead of throwing:

let audioCtx = null, analyser = null, srcFreq = null, srcTime = null, usingReal = false;

async function enableSound(mode = 'synth') {     // 'synth' | 'mic' | 'file'
  try {
    audioCtx = audioCtx || new (window.AudioContext || window.webkitAudioContext)();
    await audioCtx.resume();                      // REQUIRES a user gesture
    analyser = audioCtx.createAnalyser();
    analyser.fftSize = 1024;                       // → frequencyBinCount = 512
    analyser.smoothingTimeConstant = 0.8;
    srcFreq = new Uint8Array(analyser.frequencyBinCount);
    srcTime = new Uint8Array(analyser.frequencyBinCount);

    let node;
    if (mode === 'mic') {
      const s = await navigator.mediaDevices.getUserMedia({ audio: true });
      node = audioCtx.createMediaStreamSource(s);
      node.connect(analyser);                      // mic → analyser ONLY (no feedback)
    } else if (mode === 'file') {
      const el = new Audio(); el.src = fileURL; el.loop = true;
      node = audioCtx.createMediaElementSource(el);
      node.connect(analyser); analyser.connect(audioCtx.destination); await el.play();
    } else {
      node = buildSynth(audioCtx);                 // a looping synth you can hear
      node.connect(analyser); analyser.connect(audioCtx.destination);
    }
    usingReal = true; setStatus('live · ' + mode);
  } catch (e) {
    usingReal = false; setStatus('audio unavailable — staying synthetic (' + e.name + ')');
  }
}

3 · Read the analyser into the shared arrays

This is the heart of every Web Audio visualizer, and it's two method calls. getByteFrequencyData fills an array with the spectrum; getByteTimeDomainData fills one with the waveform. Both write 0–255 integers, so there's nothing to normalize. We call one readAudio per frame that picks the source: real analyser if enabled, synthetic math otherwise. When real, the analyser's frequencyBinCount (512 here) rarely matches our visual N (256), so we resample down into the shared arrays:

// Per frame: fill the SHARED arrays from whichever source is active.
function readAudio(t) {
  if (usingReal && analyser) {
    analyser.getByteFrequencyData(srcFreq);   // spectrum, 0..255
    analyser.getByteTimeDomainData(srcTime);  // waveform, 0..255 around 128
    resampleInto(srcFreq, spectrum);          // analyser bins → our N
    resampleInto(srcTime, waveform);
  } else {
    synthAudio(t, spectrum, waveform);         // the fake song
  }
}

// Average a longer source array down into a shorter destination.
function resampleInto(src, dst) {
  const ratio = src.length / dst.length;
  for (let i = 0; i < dst.length; i++) {
    const a = Math.floor(i * ratio), b = Math.floor((i + 1) * ratio);
    let sum = 0;
    for (let j = a; j < b; j++) sum += src[j];
    dst[i] = sum / Math.max(1, b - a);
  }
}

4 · Drawing bars from the spectrum

And the payoff: turning the array into pixels. Clear the canvas, walk the array, and for each value draw a rectangle whose height is that value mapped to the canvas height. That's it — the equalizer is a for loop. (Everything is scaled by devicePixelRatio at setup so it's crisp on retina displays.)

function drawBars(ctx, spectrum, n, W, H) {
  ctx.clearRect(0, 0, W, H);
  const bw = W / n;
  for (let i = 0; i < n; i++) {
    // average the spectrum down to n visible bars
    const v = binValue(spectrum, i, n);   // 0..255
    const h = (v / 255) * H;            // → pixel height
    ctx.fillStyle = 'hsl(' + (200 - i / n * 160) + ' 90% 60%)';
    ctx.fillRect(i * bw, H - h, bw - 1, h);  // grow up from the bottom
  }
}

Common pitfalls

  • The AudioContext starts suspended. Browsers won't let a page make sound until the user interacts, so a context created on page load sits frozen and your arrays stay all zeros. You must create and resume() it inside a real click/tap handler. (The synthetic visuals sidestep this entirely — that's a big reason this series defaults to them.)
  • frequencyBinCount is not your N. The analyser gives you fftSize / 2 bins (512 here), which almost never equals the number of bars you want to draw. Don't index your visual loop into the raw analyser array — average or stride it down into your own array first, as resampleInto does.
  • Never connect the mic to destination. A MediaStreamSource wired to the speakers is a feedback loop — an instant, painful squeal. Connect the mic to the analyser only. (Synth and file are safe to route to the speakers, since you want to hear them.)
  • The values are already 0–255. Both getByteFrequencyData and getByteTimeDomainData hand you bytes — no division, no normalization needed before you draw. If a visualization looks too dim or clipped, tune the analyser's minDecibels/maxDecibels rather than rescaling by hand.

Exercises

  1. Color the bars by frequency. In drawBars the hue is already a function of i; play with it — make bass red and treble violet, or drive lightness by the value so loud bins glow. You're mapping one array to color, the most basic audio-reactive move there is.
  2. Add a peak-hold line. Keep a second array peaks[]; each frame set peaks[i] = Math.max(spectrum[i], peaks[i] - 2) and draw a thin cap at each peak. It decays slowly, so you see the loudest recent value linger above each bar — a classic VU-meter touch.
  3. Log the loudest bin. Each frame, scan spectrum for its maximum value and that value's index, and print "bin i = v" on the canvas. Watch it jump to the bass on every kick. You've just written the seed of beat detection (Episode 03).

What's next

Episode 02 — The Bar Visualizer Done Right. The bars in stage 2 are honest but naive: music is logarithmic, so a linear bar layout crams all the interesting detail into the bass and wastes the right half on near-silent treble. Next we fix that with log-spaced frequency bands, add temporal smoothing so the bars glide instead of strobe, and bend the whole thing into a circle for that radial-spectrum look. Same two arrays — a far better visualizer.