Interactive Vision From Zero · Episode 08
Air Instrument
Air Instrument is Episode 08 of Interactive Vision 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 finale, and it's a banger: you punch the empty air in front of your webcam and a drum fires. Strum across a row of floating bars and they ring out a melody. There is no MIDI controller, no drum pad, no contact — just your two hands, a grid of glowing zones hanging in space, and a synth that turns a hard downward jab into a loud hit and a soft tap into a quiet one. People watch the clip and reach for their own keyboard before they remember there's nothing to touch.
Everything you've built this season collapses into one machine here. We track two hands at once (Ep02), map their fingertips into 3D space (Ep04), watch for a tip crossing a zone's plane with downward velocity — a "hit" — and on each hit we trigger a Web Audio note plus a visual burst, the velocity setting both the loudness and the brightness. The demo below is already playing itself: a synthetic two-hand auto-drummer is tapping out a little groove on first paint, with the lights flashing. Sound starts off (browsers forbid autoplay); hit 🔊 tap to enable sound and the groove comes alive in your speakers.
What you're looking at
A dark stage with a row of glowing slabs floating at chest height — the trigger zones. Each one is an invisible plane with a pad drawn on it: a drum pad, a harp string, or a marimba bar depending on the instrument. Two bright dots are fingertips (the index tip of each hand). When a fingertip stabs through a zone's plane while moving fast enough in the trigger direction, that pad lights up, a ripple expands from the contact point, and — once sound is enabled — a note rings out. Harder jabs flash brighter and play louder. The synthetic hands tap out a repeating little pattern so the kit is alive before you ever lift a finger; the moment you flip on your camera, your real hands drop into the exact same code.
Mirror, stated up front: this is a selfie view, so we flip the X
axis — worldX ∝ (1 − landmark.x) — for both hands. Move your hand right, the
on-screen fingertip goes right, and the pad under it is the one you'd expect. The
synthetic hands are mirrored identically, so synthetic and camera modes line up.
Mirrored axes are the number-one "why is it backwards," so we name it loudly and apply
it in exactly one place.
Stage 1 — Zones laid out
Just the instrument, no hands acting on it. A zone is dead simple: a center point in
world space, a width/height, a facing axis (which way "through" means), and a
pitch. Drums lay out as a 2×3 grid of pads; harp and marimba lay out as a single row of
vertical strings / horizontal bars. Switch the instrument selector and watch
the layout rebuild. Nothing is listening yet — this stage exists so you can see the
spatial target the hit test will fire against.
Stage 2 — Hit detection (visual only)
Now one fingertip is live and the hit test runs — but stays silent. A pad lights when a tip crosses its plane moving the right way fast enough. Crucially, a hit is an edge, not a state: we remember which side of the plane the tip was on last frame, and fire only on the frame it crosses. That single rule is what separates "one strike = one hit" from a pad that screams continuously while your finger rests on it. Watch a pad flash and immediately go quiet even if the fingertip lingers — that's the crossing edge plus a per-zone debounce doing their job.
Stage 3 — Sound on hit
The same hits, now wired to Web Audio — after you enable sound. Each
pad owns a pitch from a pentatonic scale, so no two pads can clash; whatever you
play sounds intentional. A hit builds a tiny voice — an oscillator into a gain node with
an ADSR envelope (a fast attack, a short decay/sustain, a release tail)
into the master output — schedules it at the audio clock's currentTime, and
lets it ring. This is the moment the demo stops being a light show and becomes an
instrument. If you haven't tapped 🔊 enable sound yet, the visuals still
fire; the audio is simply muted until a real user gesture unlocks the context.
Stage 4 — Velocity → volume
A real instrument is dynamic: a gentle tap is quiet, a hard slam is loud.
We already measure each fingertip's speed for the hit test, so we reuse it — the crossing
speed maps to the note's peak gain (and to the flash brightness and ripple size). A small
velocity number appears by each hit so you can read it. Drag the sensitivity
slider to scale how easily a motion counts as a hit and how hard it plays. This is the
difference between a toy that goes "beep" and something you can play expressively.
Stage 5 — Two hands
Both hands go live and the auto-drummer shows off — left and right tips each crossing
pads on their own schedule, so you get rolls and two-pad chords no single hand could
play. The key structural idea: there is one onLandmarks(hands)
handler that takes an array of hands and loops over them, each with its own
per-frame previous-position memory. Camera mode just sets numHands: 2 and
feeds the same array. Puppet one hand with your mouse and the synthetic partner keeps the
groove under you.
Stage 6 — Full kit + juice
Same machine, dressed for the stage: fingertip trails, expanding ripple rings on every hit, a soft glow bloom on struck pads, and a tiny looping groove from the auto-drummer so there's always something happening. Switch instruments live — drums for a beat, marimba for a melody, harp for a glissando when a tip sweeps across the whole row. This is where you'd hit record. It's the same handful of ideas from the stages above, turned up until it sings.
How the code works
Four pieces carry the whole episode. We'll look at each alone; in the demo they're
wired into one onLandmarks(hands) handler that both the synthetic loop and
the real camera feed call — a single source of truth, looped over two hands.
(a) Zone definition + the fingertip-velocity-crossing hit test
A zone is a plane in world space with a facing axis. The hit test is an edge detector: it checks whether the tip moved from the front side to the back side of the plane this frame, landed inside the pad's rectangle, and was moving fast enough along the facing axis. A per-zone debounce (an "armed" flag plus a cooldown timestamp) guarantees one strike fires exactly one hit — and the zone won't re-arm until the tip leaves and the cooldown elapses:
// A zone: a pad centered at `c`, size w×h, facing one axis (the "through" direction).
// axis 'z' means you punch along -z; 'y' means you chop downward (-y).
function makeZone(c, w, h, axis, pitch) {
return { c, w, h, axis, pitch,
armed: true, // must leave + cool down before it can fire again
cooldownUntil: 0, // audio-clock time the debounce expires
flash: 0 }; // 0..1 visual envelope, decays each frame
}
// tip, prevTip: THREE.Vector3 this frame and last. now: seconds. Returns hit velocity or 0.
function testHit(zone, tip, prevTip, now, sensitivity) {
const ax = zone.axis; // 'z' (punch) or 'y' (chop)
const plane = zone.c[ax];
const before = prevTip[ax] - plane; // signed distance last frame
const after = tip[ax] - plane; // signed distance this frame
// must cross from the FRONT (+) to the BACK (-): a downward/inward stab
const crossed = before > 0 && after <= 0;
if (!crossed) {
if (before > 0.25) zone.armed = true; // tip pulled back out → re-arm
return 0;
}
if (!zone.armed || now < zone.cooldownUntil) return 0; // debounce
// landed inside the pad rectangle? (the two axes that AREN'T the facing axis)
const [u, v] = ax === 'z' ? ['x', 'y'] : ['x', 'z'];
if (Math.abs(tip[u] - zone.c[u]) > zone.w*0.5) return 0;
if (Math.abs(tip[v] - zone.c[v]) > zone.h*0.5) return 0;
// crossing speed along the facing axis (world units / sec), scaled by sensitivity
const speed = Math.abs(after - before) / Math.max(dt, 1e-3) * sensitivity;
if (speed < HIT_MIN_SPEED) return 0; // too slow → a graze, not a hit
zone.armed = false; // disarm until the tip leaves
zone.cooldownUntil = now + 0.07; // 70ms lockout (no double-trigger)
return speed; // > 0 means HIT, with its velocity
}
(b) A Web Audio voice, gated behind a user gesture
The audio context starts suspended — browsers block sound until the
user acts. The 🔊 enable button is that gesture: it creates (or
resume()s) the context and a single master gain. After that, each hit builds
a throwaway voice — oscillator → gain (ADSR) → master → speakers — scheduled at the audio
clock. We never autoplay; if the context isn't running, we just skip the sound and
let the visuals carry the demo:
let audioCtx = null, master = null;
// Called ONLY from the enable-sound button's click handler — a real user gesture.
async function enableSound() {
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
master = audioCtx.createGain();
master.gain.value = 0.9; // headroom so stacked voices don't clip
master.connect(audioCtx.destination);
}
await audioCtx.resume(); // the unlock — must follow a gesture
}
// Build one note. freq in Hz, gain 0..1 (from hit velocity). Scheduled, then forgotten.
function playVoice(freq, gain, type) {
if (!audioCtx || audioCtx.state !== 'running') return; // not unlocked → silent
const t = audioCtx.currentTime; // schedule on the AUDIO clock, not JS time
const osc = audioCtx.createOscillator();
const env = audioCtx.createGain();
osc.type = type; // 'sine' marimba, 'triangle' harp, 'square' drum-ish
osc.frequency.value = freq;
// ADSR: ramp up fast, decay to a low sustain, release to silence
const A = 0.004, D = 0.09, S = 0.0, R = 0.35;
env.gain.setValueAtTime(0.0001, t);
env.gain.exponentialRampToValueAtTime(gain, t + A); // attack
env.gain.exponentialRampToValueAtTime(Math.max(0.0001, gain*0.3), t + A + D); // decay
env.gain.exponentialRampToValueAtTime(0.0001, t + A + D + R); // release
osc.connect(env).connect(master);
osc.start(t);
osc.stop(t + A + D + R + 0.02); // auto-free the node graph
}
(c) Velocity → gain, and the pentatonic pitch table
Two mappings make it sound musical. First, the pitch table: a minor pentatonic scale
repeated across octaves, so we just index it by pad number and every combination is
consonant. Second, hit velocity → gain: we normalize the crossing speed into
[0,1] with a curve (a soft knee so soft taps are still audible) and cap
polyphony so a flurry of hits can't pile up and clip the master:
// Minor pentatonic (semitone offsets) → Hz, repeated up the octaves.
const PENTA = [0, 3, 5, 7, 10]; // A minor pentatonic steps
const ROOT = 220; // A3, in Hz
function pitchFor(i) { // i = pad index, 0..n
const octave = Math.floor(i / PENTA.length);
const step = PENTA[i % PENTA.length] + octave * 12;
return ROOT * Math.pow(2, step / 12); // equal-temperament: 2^(semitones/12)
}
// Crossing speed → 0..1 gain. Soft knee keeps quiet hits audible; clamp avoids clipping.
function velToGain(speed) {
const norm = Math.min(1, speed / VEL_FULL); // VEL_FULL = speed that plays "fff"
return 0.12 + 0.78 * Math.pow(norm, 0.6); // floor + curved range
}
// Polyphony cap: count live voices; if at the ceiling, drop the new hit (or steal oldest).
if (liveVoices < MAX_VOICES) { liveVoices++; playVoice(freq, g, wave); }
(d) The two-hand loop feeding one shared handler
The whole reason two hands "just work" is that nothing downstream knows how many hands
there are. The loop fetches an array — two synthetic hands, or up to two from the camera —
and hands it to one onLandmarks(hands). Each hand carries its own
previous-fingertip position (keyed by hand index) so velocities don't bleed between them:
// per-hand previous fingertip, so each hand has independent velocity + crossing state
const prevTip = [new THREE.Vector3(), new THREE.Vector3()];
const haveTip = [false, false];
function onLandmarks(hands, now) { // hands: array of 21-landmark arrays
for (let h = 0; h < hands.length; h++) {
const tip = tipToWorld(hands[h][8], _tmp); // INDEX_TIP → world (mirrored)
if (haveTip[h]) {
for (const z of zones) { // ONE hit test, every zone × every hand
const speed = testHit(z, tip, prevTip[h], now, sensitivity);
if (speed > 0) triggerHit(z, speed, tip); // sound + visual burst
}
}
prevTip[h].copy(tip); haveTip[h] = true;
}
}
// In the loop — synthetic (always) or camera (numHands: 2), SAME array, SAME handler:
const hands = usingCamera ? cameraHands() : [syntheticHand(t, posA, optA),
syntheticHand(t, posB, optB)];
onLandmarks(hands, audioNow());
Common pitfalls
- Autoplay-blocked silence. An
AudioContextcreated on page load is suspended; nothing plays. It can only be resumed inside a real user-gesture handler (click/tap/key). So we start sound OFF, run visuals immediately, andresume()only from the enable button. Never callresume()on load — it silently fails and confuses everyone. - Double-triggers / machine-gun pads. If you fire whenever the tip is past the plane, one strike fires every frame it lingers. Detect the crossing edge (front→back this frame), then disarm the zone until the tip pulls back out, plus a short cooldown. One strike = one hit.
- Velocity sign / wrong axis. "Down" in image space is +y, but world-up is +y after the flip; "into the screen" is −z. Decide each zone's facing axis explicitly and test the crossing in that axis only, in the right direction. Get the sign backwards and pulling your hand out triggers the hit.
- Latency. Keep the audio graph tiny (osc → gain → master) and
schedule at
audioCtx.currentTime, never on asetTimeoutor the JS animation clock. Heavy per-note graphs or effects chains add audible lag between the punch and the sound. - Clipping from too many voices. Stack enough notes and the summed
signal exceeds 0 dBFS and crunches. Cap polyphony (
MAX_VOICES), keep a master gain below 1.0 for headroom, and give each voice a short release so old notes free up fast. - Mirror. Forget the
1 − xflip and your hand hits the pad on the wrong side. Apply it once, in the landmark→world mapping, to both hands and to synthetic + camera input.
Exercises
- Metronome + loop recorder. Add a scheduled click on the audio clock (a quiet voice every beat), and record the timestamps + pitches of your hits into an array. Replay the array in a loop, quantized to the beat — now you can lay down a drum pattern and play melody on top of your own loop.
- Split the hands. Map the left hand's height to pitch (a
continuous theremin-style glide) and keep the right hand for rhythmic hits.
You already have a per-hand loop and per-hand velocity — this is just reading each
hand's role differently inside
onLandmarks. - Real percussion. Swap the oscillator for a short
noise burst: fill an
AudioBufferwith random samples, play it through a fast-decaying gain and a bandpass filter whose frequency you set from the pad. Suddenly the "drums" sound like actual hits instead of beeps.
What's next — and that's Season 1
That's the season. Over eight episodes you went from "the webcam is a stream of pixels" to playing music by punching the air with both hands — and every link in the chain (camera → landmarks → gesture → action → feedback) is code you can now wire any way you like. You can take any hand motion and turn it into any response, with sound and visuals, at 60fps, entirely on-device.
Season 2 — Body & Face picks up the same playbook on a bigger canvas: the 33-point full-body pose and the 468-point face mesh. Puppet a 3D avatar with your whole body, count squats with a joint-angle state machine, build AR face filters that anchor to your features, and drive effects with gaze and blink. The synthetic-driver + lazy-camera pattern carries straight over — only the landmark model changes. (Season 2 isn't built yet; star the series index to catch it.)