Web music: master bus, echo with FX in the feedback loop, mic monitoring with a metronome, audio-clock timing, and a complete drum machine
prompts/pkg/llms/web-music.md on every deploy, so it
can't drift from what the platform actually does. Read it from your terminal any
time with npx vibes-diy skills.
Authoritative source: Issue #228 research threads — comments 3192681700, 3192696052, 3192806626.
This builds on the Web Audio doc above. The context is the sound core's
unlockAudio(), called first, synchronously, in the gesture; the core nodes and heavyweight engines that arrive by runtime import are taught there.A drum machine, beat maker or step sequencer starts from §6 — a complete, runnable one with a synthesized kit, sixteen steps, tempo, swing, saturation and volume.
1) Master bus — every audio toy ships Saturation and Volume
Every audio toy ships one master bus with a Saturation control and a Volume control that act on everything it plays. A drum machine, a synth, a generative drone, a theremin: whatever the person asked for, these two sit in the main controls with plain labels, always visible, and they shape notes that are already sounding as well as the next ones.
- Route every voice through one master
GainNodeand give the person a Volume control that sets its gain. - Put one
WaveShaperNodeon the master bus and give the person a Saturation control that sets how hard it drives.
Graph: voices → bus:GainNode → saturation:WaveShaperNode → master:GainNode → destination. Build the bus once, next to the context, and connect each new voice to bus instead of destination. Saturation at zero is a clean pass-through, so the toy sounds the same until the person turns it up.
js// Build once, beside the context (inside unlockAudio() or the engine's init).
function makeSaturationCurve(amount) {
// amount 0..1 → 0 is no curve at all (a true bypass; a straight-line curve would still
// clamp summed voices above 1.0), 1 is hard tanh drive.
if (amount === 0) return null;
const k = amount * 50;
const n = 1024;
const curve = new Float32Array(n);
for (let i = 0; i < n; i++) {
const x = (i / (n - 1)) * 2 - 1;
curve[i] = Math.tanh(k * x) / Math.tanh(k);
}
return curve;
}
const bus = audioCtx.createGain();
const saturation = audioCtx.createWaveShaper();
saturation.curve = makeSaturationCurve(0);
saturation.oversample = "4x";
const master = audioCtx.createGain();
master.gain.value = 0.8;
bus.connect(saturation).connect(master).connect(audioCtx.destination);
// Every voice lands on the bus, never on destination directly.
// voiceGain.connect(bus);
// The two global controls.
function setSaturation(amount) {
saturation.curve = makeSaturationCurve(amount);
}
function setVolume(value) {
master.gain.setTargetAtTime(value, audioCtx.currentTime, 0.02);
}
jsximport { Slider } from "@vibes.diy/ui/interactive";
<Slider label="Saturation" min={0} max={1} step={0.01} value={[drive]} onChange={([v]) => { setDrive(v); setSaturation(v); }} />
<Slider label="Volume" min={0} max={1} step={0.01} value={[volume]} onChange={([v]) => { setVolumeState(v); setVolume(v); }} />
These two sliders are for a synth, a drone, a theremin and every other audio toy. A beat app turns the same two controls as knobs: Drive and Volume sit beside Tempo and Swing as four Knobs on the drum machine's face (§6).
With an engine that arrives by runtime import (the Web Audio doc above), the same two controls sit on its output: a Tone.Distortion (or Tone.Chebyshev) before Tone.Destination, with Saturation setting the Tone.Distortion's distortion (or the Tone.Chebyshev's order), and Volume setting Tone.Destination.volume.
2) Echo/Delay with Effects Inside the Feedback Loop
Graph (node names are exact):
- Dry:
source → dryGain:GainNode → destination - Wet:
source → delay:DelayNode → wetGain:GainNode → destination - Feedback loop with FX:
delay → filter:BiquadFilterNode → distortion:WaveShaperNode → reverb:ConvolverNode → feedbackGain:GainNode → delay
Parameters to expose
delay.delayTime(s),feedbackGain.gain(0–1, keep < 1.0)filter.type,filter.frequencydistortion.curve(Float32Array)convolver.buffer(IR AudioBuffer)wetGain.gain,dryGain.gain
Notes: Prevent runaway by capping feedback below 1.0; ConvolverNode requires a loaded impulse response; zero-delay cycles are disallowed.
jsconst delay = audioCtx.createDelay(5.0);
const feedbackGain = audioCtx.createGain();
const filter = audioCtx.createBiquadFilter();
const distortion = audioCtx.createWaveShaper();
const reverb = audioCtx.createConvolver();
const wetGain = audioCtx.createGain();
const dryGain = audioCtx.createGain();
delay.delayTime.value = 0.35;
feedbackGain.gain.value = 0.5; // < 1.0
filter.type = "lowpass";
filter.frequency.value = 8000;
// distortion.curve = yourFloat32Curve;
// reverb.buffer = yourImpulseResponseAudioBuffer;
wetGain.gain.value = 0.4;
dryGain.gain.value = 1.0;
// Dry and wet
source.connect(dryGain).connect(audioCtx.destination);
source.connect(delay);
delay.connect(wetGain).connect(audioCtx.destination);
// Feedback with FX
delay.connect(filter);
filter.connect(distortion);
distortion.connect(reverb);
reverb.connect(feedbackGain);
feedbackGain.connect(delay);
Helper (load IR):
jsasync function loadImpulseResponse(url) {
const res = await fetch(url, { mode: "cors" });
if (!res.ok) throw new Error(`Failed to fetch IR ${url}: ${res.status} ${res.statusText}`);
const ab = await res.arrayBuffer();
try {
return await audioCtx.decodeAudioData(ab);
} catch (err) {
console.error("decodeAudioData failed for IR", url, err);
throw err; // Surface decoding/CORS-related failures clearly
}
}
3) Microphone Monitoring + Metronome Overlay
Mic capture: open the stream with the mic helpers' openMic(MUSIC) from the same tap that runs unlockAudio(), then create a MediaStreamAudioSourceNode and route it to a GainNode → destination. Stop the stream's tracks when monitoring ends.
Metronome: synthesize a short click (e.g., square/sine burst through a gain envelope). Schedule by audio clock at AudioContext.currentTime with lookahead.
Mix graph: micGain + metronomeGain → master → destination.
jsconst master = audioCtx.createGain();
master.connect(audioCtx.destination);
const micGain = audioCtx.createGain();
const metronomeGain = audioCtx.createGain();
micGain.connect(master);
metronomeGain.connect(master);
// From the Start tap, after unlockAudio(). A refusal comes back as { ok: false, reason }.
async function initMic() {
const mic = await openMic(MUSIC);
if (mic.ok) audioCtx.createMediaStreamSource(mic.stream).connect(micGain);
return mic;
}
function scheduleClick(atTime, downbeat = false) {
const osc = audioCtx.createOscillator();
const env = audioCtx.createGain();
osc.type = "square";
osc.frequency.setValueAtTime(downbeat ? 2000 : 1600, atTime);
env.gain.setValueAtTime(0.0001, atTime);
env.gain.exponentialRampToValueAtTime(1.0, atTime + 0.001);
env.gain.exponentialRampToValueAtTime(0.0001, atTime + 0.03);
osc.connect(env).connect(metronomeGain);
osc.start(atTime);
osc.stop(atTime + 0.05);
// Cleanup to avoid accumulating nodes during long sessions
osc.onended = () => {
try {
osc.disconnect();
} catch {}
try {
env.disconnect();
} catch {}
};
}
function startMetronome({ bpm = 120, beatsPerBar = 4 } = {}) {
const spb = 60 / bpm; // seconds per beat
let next = audioCtx.currentTime + 0.1;
let beat = 0;
const lookaheadMs = 25,
ahead = 0.2;
const id = setInterval(() => {
while (next < audioCtx.currentTime + ahead) {
scheduleClick(next, beat % beatsPerBar === 0);
next += spb;
beat = (beat + 1) % beatsPerBar;
}
}, lookaheadMs);
return () => clearInterval(id);
}
Latency and safety: start/resume on user gesture; clean up per-tick nodes after ended to prevent buildup in long-running metronomes; use headphones while monitoring; mobile devices have higher base latency.
4) Time Synchronization and Scheduling Model
Clocks/time domains
- Master:
AudioContext.currentTime— sample-accurate; schedule everything on this timeline. - UI/high-res:
performance.now()— for UI timers and Web MIDI timestamps. - Mapping: capture
(tPerf0 = performance.now(), tAudio0 = audioCtx.currentTime), convert MIDI/perf timestamps withtAudio = tAudio0 + (timeStamp - tPerf0)/1000. - Hints:
audioCtx.baseLatency,audioCtx.getOutputTimestamp?.()— estimate DAC/output delay if aligning to “heard” time.
Scheduling primitives
AudioBufferSourceNode.start(when, offset?, duration?)for one-shots/loops.AudioParamautomation (setValueAtTime,linearRampToValueAtTime,setTargetAtTime,setValueCurveAtTime).- Avoid
requestAnimationFrame/setTimeoutfor timing; use an AudioWorklet for custom DSP/tight jitter when needed.
Tempo transport and lookahead
- Tempo mapping:
secondsPerBeat = 60 / bpm; compute bars:beats:ticks → seconds on the audio clock (choose PPQ, e.g., 480/960). - Lookahead window: maintain ~50–200 ms rolling schedule; enqueue with absolute
whentimes in audio seconds.
Multi‑channel sample playback
- Pre‑decode all samples; never decode on hit.
- Per hit: create a fresh
AudioBufferSourceNodeand call.start(when). - For phase‑aligned layers (kick+clap, etc.), schedule all sources with the same
whento guarantee sample‑accurate overlap. - Routing: per‑track
GainNode/optional FX → master bus; allow overlapping retriggers; compute flams as smallwhenoffsets. - Pattern changes: compute the next bar boundary on the audio clock and enqueue new pattern hits relative to that time.
MIDI synth playback
- Live input: map
MIDIMessageEvent.timeStamp(perf.now domain) → audio clock as above; buffer a short lookahead (5–20 ms) to reduce jitter. - SMF playback: convert PPQ ticks using the tempo map; schedule noteOn/noteOff separately; sustain (CC64) defers noteOff until pedal release.
- Voice management: one voice per active note; allow overlapping envelopes; define voice‑steal policy if a polyphony cap is hit.
External sync and drift
- For MIDI Clock/MTC, derive BPM/phase from incoming ticks, convert to audio time, and drive the transport. Correct small phase error between beats with bounded micro‑nudges—avoid discontinuities.
5) File layout — audio apps split, proactively
Audio apps run long: an engine (context/graph/scheduler), a playable surface (keyboard, pads, step grid), transport/parameter controls, and a preset list each carry real code. A single-file synth blows past the ~500-line App.jsx split threshold almost immediately — so split from the start rather than after the fact. The sandbox serves raw ES modules: relative imports work, local .css imports do not (style stays in App.jsx).
The shape that works (filenames illustrative — split by responsibility, matched to the app's actual surfaces, not by count):
lib/audio-engine.js— everything that touchesAudioContext: theunlockAudio()gate, node graph construction, voice management, the lookahead scheduler. Plain module, no React; export functions/objects the UI calls. Keeping the engine React-free is what makes gesture-synchronous unlock (the sound core) and clean scheduling (§4) easy — no re-render can rebuild the graph.components/Keyboard.jsx(orStepGrid.jsx,Pads.jsx) — the playable surface; calls engine functions frompointerdown-family handlers.components/TransportControls.jsx,components/PresetList.jsx— parameter knobs/sliders and preset browsing; presets live in the database, the engine consumes plain parameter objects.App.jsx— layout, styling, database wiring; imports the above (import { createEngine } from "./lib/audio-engine.js").
6) A complete drum machine — the shell every beat vibe starts from
Every pad is an instrument from the first tap. A tap that switches a step
on while the beat is stopped plays that voice at once, so the person hears
what they placed before they press Play. The step handler is this shape, and
the App.jsx below carries it as toggleStep:
jsxfunction toggleStep(track, i) {
const engine = drums(); // getDrums() on the tap itself: it unlocks sound on iOS
const on = !grid[track][i];
setGrid({ ...grid, [track]: grid[track].map((v, j) => (j === i ? (on ? 1 : 0) : v)) });
if (on && !playing) engine.hit(track); // hear the sound you just placed
}
Build the first version of any beat app (a drum machine, beat maker, step
sequencer or groovebox) from this section: the engine as written, and an
instrument face whose picks you choose (§ "Make it yours" below). The
data-instrument panel is how a drum machine looks from its very first build,
under any look, layout or skin the turn also carries.
Every beat app's first build wears the whole face, copied from the
App.jsx below: Panel (the bezel, four corner screws and a printed name
plate), Transport (Play, Clear and the recessed tempo readout), Knobs
(Tempo, Swing, Drive and Volume, each a turning Knob), Lights (the row of
step lights that follows the playing step) and one arrangement of the pads.
The knob is the one control this face draws itself: where the builder's rules
say a slider is Slider, an instrument's Tempo, Swing, Drive and Volume are
still Knobs, because turning a knob is what makes it read as a machine.
Three arrangements, one per app. The App.jsx ends with three
arrangement sketches of the same parts, and each makes a different machine:
- rows (
RowsPanel): every voice a line of sixteen steps, the classic drum machine; - pad grid (
PadGridPanel): four big voice pads choose a sound, and that voice's sixteen steps sit four by four, MPC style; - vertical rack (
RackPanel): each voice its own rack unit with a name plate, a Hit button and its step row, stacked like studio gear.
The turn's "Instrument arrangement" section names this app's arrangement. With
no such section, choose the one that suits what the person asked for and what
the app is about: a pad grid for finger drumming and big taps on a phone, a rack
for a studio or a layered kit, rows for a classic pattern machine. Each is as
good a first build as the others, so rows is one choice of three. App sets
ARRANGEMENT to the chosen name and renders that sketch.
This is a two-file kit: a synthesized four-voice kit (kick, snare, closed and open hat), a sixteen-step sequencer, tempo and swing, and global saturation and volume on the master bus. No samples, no downloads — every sound is built from oscillators and noise, so it plays the moment the person taps. Start here for any drum machine, beat maker, step sequencer or groovebox and grow it: more voices, more steps, accents, pattern banks.
Why it sounds good, in four moves:
- Kick — a sine that sweeps 150 Hz → 55 Hz in 50 ms, then settles to 45 Hz: the sweep is the punch, the tail is the boom. A few milliseconds of band-passed noise on top is the beater, so the kick still reads on phone speakers that cannot reproduce 45 Hz.
- Snare — two tuned triangle "shell" tones under high-passed noise with a presence lift at 5 kHz for the wires.
- Hats — the 808 recipe: six square waves at inharmonic ratios of 40 Hz, band-passed at 10 kHz and high-passed at 7 kHz. A closed hat chokes a ringing open hat through the open hat's own gate gain, like the real machine.
- Master bus — voices → bus (headroom) → drive gain →
tanhWaveShaper (4× oversampled, so the new harmonics do not alias into fizz) → makeup gain → volume → a fastDynamicsCompressoras a limiter. The makeup gain falls as the drive rises, so Saturation changes the colour, not the loudness; Volume is squared so the slider feels even.
The engine is a plain module (§5): the sound core's gate, the lookahead scheduler
from §4, and a playhead() the interface polls each animation frame, so the
lit step follows what is reaching the speakers rather than the timer. The steps
are StepGrid rows of Pads from @vibes.diy/ui/interactive: square pads
in beats of four, a light on the playing step, sixteen across on a laptop and
eight a line on a phone. A pad is an instrument's square, so the grid reads as a
drum machine, never as a column of settings toggles; a single Pad is the
finger-drumming pad of an MPC-style kit or a launch cell. The
interface calls getDrums() synchronously at the top of every tap handler —
Play, and each step — which is what unlocks sound on iOS.
lib/drum-engine.js
js// Everything that touches AudioContext lives here — no React, so a re-render never rebuilds the graph.
export const STEPS = 16;
export const TRACKS = [
{ id: "kick", label: "Kick" },
{ id: "snare", label: "Snare" },
{ id: "closed", label: "Closed hat" },
{ id: "open", label: "Open hat" },
];
let audioCtx;
let drums;
// The sound core's gate: synchronous, inside the tap, with one real (silent) sound.
function unlockAudio() {
// A drum machine's point is sound: play with the iPhone's silent switch on (web-audio § 2b).
if ("audioSession" in navigator) navigator.audioSession.type = "playback";
audioCtx ||= new (window.AudioContext || window.webkitAudioContext)();
if (audioCtx.state !== "running") {
audioCtx.resume();
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
gain.gain.value = 0.0001;
osc.connect(gain).connect(audioCtx.destination);
osc.start();
osc.stop(audioCtx.currentTime + 0.01);
}
return audioCtx;
}
// Call from a tap handler, synchronously: unlocks audio and builds the one engine on that context.
export function getDrums() {
const ctx = unlockAudio();
drums ||= createDrums(ctx);
return drums;
}
function createDrums(ctx) {
const settings = { pattern: {}, bpm: 112, swing: 0, drive: 0.3, volume: 0.8 };
// Master chain: voices → bus → drive → tanh shaper → makeup → volume → limiter → speakers.
const bus = ctx.createGain();
const drive = ctx.createGain();
const shaper = ctx.createWaveShaper();
const makeup = ctx.createGain();
const volume = ctx.createGain();
const limiter = ctx.createDynamicsCompressor();
bus.gain.value = 0.7; // headroom: a kick and a hat on the same step stay under full scale
shaper.curve = tanhCurve(MAX_DRIVE);
shaper.oversample = "4x"; // keeps the new harmonics from folding back down as fizz
limiter.threshold.value = -3;
limiter.knee.value = 0;
limiter.ratio.value = 20;
limiter.attack.value = 0.002;
limiter.release.value = 0.1;
bus.connect(drive).connect(shaper).connect(makeup).connect(volume).connect(limiter).connect(ctx.destination);
const noise = noiseBuffer(ctx);
const live = new Set(); // every scheduled source and its start time, so Stop can cancel the future
let openChoke = null; // the ringing open hat's gate — a closed hat shuts it, like the real machine
function chokeOpen(at) {
openChoke?.gain.setTargetAtTime(0, at, 0.006);
openChoke = null;
}
function play(source, at, end, nodes = []) {
const entry = { source, at };
live.add(entry);
source.onended = () => {
live.delete(entry);
source.disconnect();
for (const node of nodes) node.disconnect();
};
source.start(at);
source.stop(end);
}
// A percussive envelope: 2 ms attack, exponential decay to silence.
function envelope(at, peak, decay, out = bus) {
const amp = ctx.createGain();
amp.gain.setValueAtTime(0.0001, at);
amp.gain.exponentialRampToValueAtTime(peak, at + 0.002);
amp.gain.exponentialRampToValueAtTime(0.0001, at + decay);
amp.connect(out);
return amp;
}
function filter(type, frequency, q = 0.7) {
const node = ctx.createBiquadFilter();
node.type = type;
node.frequency.value = frequency;
node.Q.value = q;
return node;
}
// 808-style metal: six square waves at inharmonic ratios, band-passed high.
function hat(at, decay, peak, out) {
const band = filter("bandpass", 10000);
const high = filter("highpass", 7000);
const amp = envelope(at, peak, decay, out);
band.connect(high).connect(amp);
[2, 3, 4.16, 5.43, 6.79, 8.21].forEach((ratio, i) => {
const osc = ctx.createOscillator();
osc.type = "square";
osc.frequency.value = 40 * ratio;
osc.connect(band);
play(osc, at, at + decay + 0.02, i === 0 ? [band, high, amp] : []);
});
}
const voices = {
kick(at) {
// A sine that drops from 150 Hz to 45 Hz: the pitch sweep is the punch, the tail is the boom.
const body = ctx.createOscillator();
body.frequency.setValueAtTime(150, at);
body.frequency.exponentialRampToValueAtTime(55, at + 0.05);
body.frequency.exponentialRampToValueAtTime(45, at + 0.4);
const amp = envelope(at, 1, 0.5);
body.connect(amp);
play(body, at, at + 0.55, [amp]);
// The beater: a few ms of filtered noise, so the kick still reads on phone speakers.
const click = ctx.createBufferSource();
click.buffer = noise;
const tone = filter("bandpass", 3500, 0.8);
const clickAmp = envelope(at, 0.3, 0.012);
click.connect(tone).connect(clickAmp);
play(click, at, at + 0.03, [tone, clickAmp]);
},
snare(at) {
// Two tuned shell tones under a bright burst of noise for the wires.
for (const [freq, level] of [[185, 0.45], [330, 0.25]]) {
const shell = ctx.createOscillator();
shell.type = "triangle";
shell.frequency.setValueAtTime(freq, at);
shell.frequency.exponentialRampToValueAtTime(freq * 0.85, at + 0.1);
const amp = envelope(at, level, 0.14);
shell.connect(amp);
play(shell, at, at + 0.16, [amp]);
}
const wires = ctx.createBufferSource();
wires.buffer = noise;
const high = filter("highpass", 1500);
const air = filter("peaking", 5000);
air.gain.value = 6;
const amp = envelope(at, 0.6, 0.22);
wires.connect(high).connect(air).connect(amp);
play(wires, at, at + 0.25, [high, air, amp]);
},
closed(at) {
chokeOpen(at);
hat(at, 0.06, 0.32, bus);
},
open(at) {
chokeOpen(at); // one open hat at a time, so the next closed hat always silences it
openChoke = ctx.createGain();
openChoke.connect(bus);
hat(at, 0.45, 0.24, openChoke);
},
};
// The scheduler: a 25 ms timer tops up 120 ms of sound ahead of the audio clock (§4).
const LOOKAHEAD = 0.12;
let timer = 0;
let step = 0;
let gridTime = 0;
let lit = -1;
const lights = []; // { step, at }: the playhead follows the sound, not the timer
function tick() {
const sixteenth = 60 / settings.bpm / 4;
// A throttled background tab can fall far behind the audio clock: skip the missed steps
// (keeping the beat's phase) instead of scheduling a burst of hits in the past.
if (gridTime < ctx.currentTime) {
const missed = Math.ceil((ctx.currentTime - gridTime) / sixteenth);
gridTime += missed * sixteenth;
step = (step + missed) % STEPS;
}
while (gridTime < ctx.currentTime + LOOKAHEAD) {
// Swing pushes every off-beat sixteenth late; 1 is a full triplet shuffle.
const at = gridTime + (step % 2 ? (settings.swing * sixteenth) / 3 : 0);
for (const { id } of TRACKS) if (settings.pattern[id]?.[step]) voices[id](at);
lights.push({ step, at });
gridTime += sixteenth;
step = (step + 1) % STEPS;
}
}
function update(next) {
Object.assign(settings, next);
const now = ctx.currentTime;
// Drive 0 is warm, 1 is crunchy. Makeup gain keeps loudness level as the drive rises,
// so the slider changes the colour, not the volume.
const gain = 1 + settings.drive * (MAX_DRIVE - 1);
drive.gain.setTargetAtTime(gain / MAX_DRIVE, now, 0.02);
makeup.gain.setTargetAtTime(1.3 / Math.sqrt(gain), now, 0.02);
volume.gain.setTargetAtTime(settings.volume ** 2, now, 0.02); // squared, so the slider feels even
}
update({});
return {
update,
start() {
if (timer) return;
step = 0;
gridTime = ctx.currentTime + 0.05;
tick();
timer = setInterval(tick, 25);
},
stop() {
clearInterval(timer);
timer = 0;
lights.length = 0;
lit = -1;
// Cancel every hit that is scheduled but not yet sounding; ringing tails finish on their own.
for (const entry of live) if (entry.at > ctx.currentTime) entry.source.stop();
},
// Audition one sound now — a tap on a step while stopped.
hit(id) {
voices[id](ctx.currentTime + 0.005);
},
// The newest step whose sound has reached the speakers; poll it from requestAnimationFrame.
playhead() {
// currentTime is what the engine has rendered; subtract the output latency for what is heard
// (it matters on Bluetooth headphones).
const heard = ctx.currentTime - (ctx.outputLatency || ctx.baseLatency || 0);
while (lights.length && lights[0].at <= heard) lit = lights.shift().step;
return lit;
},
};
}
const MAX_DRIVE = 10;
// tanh(MAX_DRIVE·x) across the shaper's −1…1 input; the drive gain picks how far up the curve we go.
function tanhCurve(k) {
const curve = new Float32Array(4096);
for (let i = 0; i < curve.length; i++) curve[i] = Math.tanh(k * ((i / (curve.length - 1)) * 2 - 1));
return curve;
}
function noiseBuffer(ctx) {
const buffer = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
return buffer;
}
A tap on a step toggles it, and while stopped it plays that sound so the
person hears what they placed. Every knob writes through to the engine, and
the scheduler reads the settings on its next step, so edits land in time
without a restart. Grooves save to the database as one document each; the
save button waits on can.create, the same verdict the server enforces.
App.jsx
jsx// The parts every arrangement shares. `App` composes them with one of the three arrangements below.
import React, { useEffect, useRef, useState } from "react";
import { Button, Row, Spacer, Stack } from "@vibes.diy/ui";
import { StepGrid } from "@vibes.diy/ui/interactive";
import { STEPS, TRACKS, getDrums } from "./lib/drum-engine.js";
const START = {
kick: [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
snare: [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
closed: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0],
open: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
};
const FACE = `
/* picks: arrangement = … · pad = … · panel = … · led = … · transport = … (name yours; this sheet's defaults are square key, brushed, --info) */
[data-instrument] {
--panel: color-mix(in oklab, var(--surface) 80%, var(--ink));
--well: color-mix(in oklab, var(--surface) 75%, var(--ink));
--screen: color-mix(in oklab, var(--surface) 88%, var(--ink));
--led: var(--info);
--pad-off: color-mix(in oklab, var(--surface) 90%, var(--ink));
position: relative; display: grid; gap: var(--s3); padding: var(--s5) var(--s3) var(--s3);
border: 2px solid var(--ink); border-radius: var(--r-card); color: var(--ink);
background: repeating-linear-gradient(90deg, var(--panel) 0 2px, color-mix(in oklab, var(--panel) 92%, var(--surface)) 2px 4px);
box-shadow: inset 0 1px 0 color-mix(in oklab, var(--surface) 60%, transparent), 0 6px 0 color-mix(in oklab, var(--ink) 70%, transparent);
}
[data-instrument] .ix-screw { position: absolute; width: 10px; height: 10px; border-radius: 50%; border: 1px solid var(--ink);
background: radial-gradient(circle at 35% 35%, var(--surface), var(--well)); }
[data-instrument] .ix-screw--tl { top: 8px; left: 8px; } [data-instrument] .ix-screw--tr { top: 8px; right: 8px; }
[data-instrument] .ix-screw--bl { bottom: 8px; left: 8px; } [data-instrument] .ix-screw--br { bottom: 8px; right: 8px; }
[data-instrument] .ix-plate { justify-self: start; padding: 4px 10px; border: 1px solid var(--ink); border-radius: var(--r-control);
background: var(--surface); font: 700 12px/1.3 var(--font-family); letter-spacing: .16em; text-transform: uppercase; }
[data-instrument] .ix-label { font-size: 11px; letter-spacing: .14em; text-transform: uppercase; color: color-mix(in oklab, var(--ink) 75%, var(--panel)); }
[data-instrument] .ix-well { display: grid; gap: var(--s2); padding: var(--s2); border-radius: var(--r-control); background: var(--well);
box-shadow: inset 0 2px 5px color-mix(in oklab, var(--ink) 45%, transparent); }
[data-instrument] .ix-lcd { padding: 4px 10px; border-radius: 4px; border: 1px solid var(--ink); background: var(--screen);
box-shadow: inset 0 2px 4px color-mix(in oklab, var(--ink) 35%, transparent); font: 700 18px/1.2 ui-monospace, monospace;
font-variant-numeric: tabular-nums; color: color-mix(in oklab, var(--ink) 80%, var(--led));
text-shadow: 0 0 6px color-mix(in oklab, var(--led) 50%, transparent); }
[data-instrument] .ix-lights { display: grid; grid-template-columns: repeat(16, 1fr); gap: 4px; }
[data-instrument] .ix-light { height: 6px; border-radius: 3px; background: color-mix(in oklab, var(--led) 18%, var(--well)); }
[data-instrument] .ix-light[data-on] { background: var(--led); box-shadow: 0 0 8px var(--led); }
[data-instrument] .ui-pad { border: 1px solid var(--ink); border-radius: 4px; box-shadow: 0 3px 0 var(--ink); }
[data-instrument] .ui-pad[data-state="off"] { background: var(--pad-off); }
[data-instrument] .ui-pad[data-state="on"][data-group="0"] { background: var(--purple); }
[data-instrument] .ui-pad[data-state="on"][data-group="1"] { background: var(--orange); }
[data-instrument] .ui-pad[data-state="on"][data-group="2"] { background: var(--up); }
[data-instrument] .ui-pad[data-state="on"][data-group="3"] { background: color-mix(in oklab, var(--purple) 50%, var(--orange)); }
[data-instrument] .ui-pad[data-state="on"] .ui-pad__led { background: var(--on-accent); box-shadow: 0 0 8px var(--on-accent); }
[data-instrument] .ui-pad__ring { box-shadow: inset 0 0 0 3px var(--led), 0 0 10px var(--led); }
[data-instrument] .ix-knob { display: grid; justify-items: center; gap: 4px; }
[data-instrument] .ix-knob__cap { position: relative; width: 56px; height: 56px; border-radius: 50%; border: 2px solid var(--ink);
touch-action: none; cursor: ns-resize; box-shadow: 0 3px 0 var(--ink);
background: radial-gradient(circle at 40% 35%, color-mix(in oklab, var(--surface) 92%, var(--ink)), var(--well) 72%);
transform: rotate(calc(-135deg + var(--turn) * 270deg)); }
[data-instrument] .ix-knob__cap::after { content: ""; position: absolute; left: calc(50% - 2px); top: 5px; width: 4px; height: 16px;
border-radius: 2px; background: var(--led); box-shadow: 0 0 6px var(--led); }
[data-instrument] .ix-knob__cap:focus-visible { outline: 3px solid var(--ink); outline-offset: 3px; }
/* arrangement helpers: a pad grid lays one voice's steps four by four; a rack stacks voice units */
[data-instrument] .ix-grid4 .ui-stepgrid { --ui-steps: 4; --ui-steps-narrow: 4; }
[data-instrument] .ix-voices { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--s2); }
[data-instrument] .ix-unit { position: relative; display: grid; gap: var(--s2); padding: var(--s3); border: 1px solid var(--ink);
border-radius: var(--r-control); background: var(--well); }
`;
// A knob turns: drag up to raise it, arrow keys step it. Its value shows on a small readout.
function Knob({ label, value, min, max, shown, onChange }) {
const drag = useRef(null);
const clamp = (v) => Math.min(max, Math.max(min, Math.round(v)));
const turn = { "--turn": (value - min) / (max - min) };
return (
<div className="ix-knob">
<div
role="slider"
tabIndex={0}
aria-label={label}
aria-valuemin={min}
aria-valuemax={max}
aria-valuenow={value}
className="ix-knob__cap"
style={turn}
onPointerDown={(e) => {
e.currentTarget.setPointerCapture(e.pointerId);
drag.current = { y: e.clientY, v: value };
}}
onPointerMove={(e) => drag.current && onChange(clamp(drag.current.v + ((drag.current.y - e.clientY) / 160) * (max - min)))}
onPointerUp={() => (drag.current = null)}
onPointerCancel={() => (drag.current = null)}
onKeyDown={(e) => {
const d = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1 }[e.key];
if (d) {
e.preventDefault();
onChange(clamp(value + d));
}
}}
/>
<span className="ix-label">{label}</span>
<span className="ix-lcd">{shown}</span>
</div>
);
}
// The engine wiring every arrangement shares: state, the iOS unlock, and a playhead that follows the sound.
function useDrumMachine() {
const [grid, setGrid] = useState(START);
const [bpm, setBpm] = useState(112);
const [swing, setSwing] = useState(0);
const [drive, setDrive] = useState(30);
const [volume, setVolume] = useState(80);
const [playing, setPlaying] = useState(false);
const [step, setStep] = useState(-1);
const drumsRef = useRef(null);
const settings = { pattern: grid, bpm, swing: swing / 100, drive: drive / 100, volume: volume / 100 };
useEffect(() => {
drumsRef.current?.update(settings);
}, [grid, bpm, swing, drive, volume]);
useEffect(() => () => drumsRef.current?.stop(), []);
useEffect(() => {
if (!playing) return;
let raf = 0;
const frame = () => {
setStep(drumsRef.current.playhead());
raf = requestAnimationFrame(frame);
};
raf = requestAnimationFrame(frame);
return () => cancelAnimationFrame(raf);
}, [playing]);
// Called synchronously at the top of every tap handler: that is what unlocks audio on iOS.
function drums() {
const engine = getDrums();
if (!drumsRef.current) engine.update(settings);
drumsRef.current = engine;
return engine;
}
function togglePlay() {
const engine = drums();
if (playing) {
engine.stop();
setStep(-1);
} else engine.start();
setPlaying(!playing);
}
function toggleStep(track, i) {
const engine = drums();
const on = !grid[track][i];
setGrid({ ...grid, [track]: grid[track].map((v, j) => (j === i ? (on ? 1 : 0) : v)) });
if (on && !playing) engine.hit(track); // hear the sound you just placed
}
const hit = (track) => drums().hit(track);
const clear = () => setGrid(Object.fromEntries(TRACKS.map(({ id }) => [id, Array(STEPS).fill(0)])));
return { grid, setGrid, bpm, setBpm, swing, setSwing, drive, setDrive, volume, setVolume, playing, step, togglePlay, toggleStep, hit, clear };
}
// Four corner screws; a rack unit carries its own set.
function Screws() {
return ["tl", "tr", "bl", "br"].map((at) => <span key={at} className={`ix-screw ix-screw--${at}`} aria-hidden="true" />);
}
// The panel itself: bezel, sheet, screws and a printed name plate.
function Panel({ label, plate, children }) {
return (
<section data-instrument aria-label={label}>
<style>{FACE}</style>
<Screws />
<span className="ix-plate">{plate}</span>
{children}
</section>
);
}
// Sixteen step lights; the lit one follows the playhead.
function Lights({ step }) {
return (
<div className="ix-lights" aria-hidden="true">
{Array.from({ length: STEPS }, (_, i) => (
<span key={i} className="ix-light" data-on={i === step || undefined} />
))}
</div>
);
}
// Play, Clear and the tempo readout.
function Transport({ m }) {
return (
<Row gap={3} align="center" wrap>
<Button onClick={m.togglePlay}>{m.playing ? "Stop" : "Play"}</Button>
<Button size="sm" variant="quiet" onClick={m.clear}>
Clear
</Button>
<Spacer />
<span className="ix-lcd">{String(m.bpm).padStart(3, "0")} BPM</span>
</Row>
);
}
// Tempo, Swing, Drive and Volume: four 56px knobs fit a phone's width in one row.
function Knobs({ m }) {
return (
<Row gap={2} align="center" justify="between">
<Knob label="Tempo" value={m.bpm} min={60} max={180} shown={m.bpm} onChange={m.setBpm} />
<Knob label="Swing" value={m.swing} min={0} max={100} shown={`${m.swing}%`} onChange={m.setSwing} />
<Knob label="Drive" value={m.drive} min={0} max={100} shown={`${m.drive}%`} onChange={m.setDrive} />
<Knob label="Volume" value={m.volume} min={0} max={100} shown={`${m.volume}%`} onChange={m.setVolume} />
</Row>
);
}
// Three arrangements. Choose one, name it in the picks line and in ARRANGEMENT at the end; App renders
// it after `const m = useDrumMachine();`. Saving, sharing and the list of saved beats are the app's own,
// built from the Fireproof and access docs as ordinary Cards outside the panel.
// Rows: every voice is a line of steps, the classic drum machine.
function RowsPanel({ m }) {
return (
<Panel label="Drum machine" plate="Jam box · 16-step">
<Transport m={m} />
<Knobs m={m} />
<Lights step={m.step} />
<div className="ix-well">
{TRACKS.map(({ id, label }) => (
<Stack key={id} gap={1}>
<span className="ix-label">{label}</span>
<StepGrid label={label} steps={m.grid[id]} playhead={m.step} onToggle={(i) => m.toggleStep(id, i)} />
</Stack>
))}
</div>
</Panel>
);
}
// Pad grid: big voice pads choose a sound (and play it); its sixteen steps sit four by four.
function PadGridPanel({ m }) {
const [voice, setVoice] = useState(TRACKS[0].id);
return (
<Panel label="Drum pads" plate="Pad 16">
<div className="ix-voices">
{TRACKS.map(({ id, label }) => (
<Button key={id} variant={voice === id ? undefined : "quiet"} onClick={() => { m.hit(id); setVoice(id); }}>
{label}
</Button>
))}
</div>
<div className="ix-well ix-grid4">
<StepGrid label={voice} steps={m.grid[voice]} playhead={m.step} onToggle={(i) => m.toggleStep(voice, i)} />
</div>
<Transport m={m} />
<Knobs m={m} />
</Panel>
);
}
// Vertical rack: each voice is its own rack unit, stacked, with its name plate and a hit button.
function RackPanel({ m }) {
return (
<Panel label="Drum rack" plate="Rack · 4 voices">
<Transport m={m} />
{TRACKS.map(({ id, label }) => (
<div key={id} className="ix-unit">
<Screws />
<Row gap={2} align="center">
<span className="ix-plate">{label}</span>
<Spacer />
<Button size="sm" variant="quiet" onClick={() => m.hit(id)}>
Hit
</Button>
</Row>
<StepGrid label={label} steps={m.grid[id]} playhead={m.step} onToggle={(i) => m.toggleStep(id, i)} />
</div>
))}
<Knobs m={m} />
</Panel>
);
}
// The arrangement this app wears: the turn's "Instrument arrangement", or the one that suits the ask.
const ARRANGEMENT = "pad grid"; // "rows" · "pad grid" · "vertical rack"
const ARRANGEMENTS = { rows: RowsPanel, "pad grid": PadGridPanel, "vertical rack": RackPanel };
export default function App() {
const m = useDrumMachine();
const Machine = ARRANGEMENTS[ARRANGEMENT];
return (
<Stack gap={4}>
<Machine m={m} />
</Stack>
);
}
The instrument face — hardware painted from the look
Every drum machine wears an instrument face from its first build: one
<section data-instrument> panel that holds the pads, the transport and the
knobs, so it reads as a machine you could pick up. The face is the app's own
instrument, so a look brief, a layout archetype or a reskin dose on the same
turn dresses the page around it, and the face keeps its knobs, pads and
token-painted panel. The heading, the save row and the saved list stay ordinary
Cards outside the panel, so the rest of the app keeps the look's own
components. When the person names a machine or a material ("an 808", "a
vintage beat box", "an MPC", "brushed metal"), this face is how it gets there.
Paint from the look's tokens. Every colour in the face is a color-mix of
the look's tokens: --bg --surface --ink --purple --orange --info --up --on-accent, with --r-card --r-control for corners and --font-family for
type. The face assigns no value to a token and writes no hex colour, so the
Look tab's colours and every look in the look picker, light and dark,
repaint the whole machine, and each look gives the same
drum machine a different body. Every fill starts from --surface. The panel,
the well, the readout window, the knob caps and the unlit pads are --surface
with a small share of --ink (75% --surface or more), so they stay a body
the look's own colour on light looks and on dark ones like Terminal, where
--ink is the light colour. Text, borders, bezels and shadows are where --ink
leads. The readout is a recessed --surface window with --ink glyphs tinted
by the LED colour, readable in both polarities; the LEDs are the LED role on
that body. Focus outlines are --ink, since an LED colour can sit close to the
panel.
The pads stay StepGrid. Style them from the panel through their hooks:
.ui-pad[data-state="on"] and [data-state="off"] (give both a fill, because
a look's button rule paints a pad otherwise), [data-group] (0 to 3 across a
bar), [data-playhead], .ui-pad__led and .ui-pad__ring.
Make it yours: every first build chooses one per axis and names the picks
as the first line of FACE, in the reference's shape:
/* picks: arrangement = … · pad = … · panel = … · led = … · transport = … */.
Choose from what the person asked for and what the app is about; when the
turn carries an "Instrument arrangement" section, that is this app's
arrangement. The
reference's picks are one combination; keep one only when it is the right one
for this app, so two drum machines rarely share all five. Each pick is a few
lines of the sheet or the markup.
Arrangement: tracks as rows (one
StepGridper voice, stacked:RowsPanel); a pad grid (four big voice pads choose which voice to edit, and a singleStepGridfor that voice is laid out four by four with--ui-steps: 4; --ui-steps-narrow: 4on.ui-stepgrid, MPC style:PadGridPanel); or a vertical rack (each voice its own rack unit, stacked: a name plate, a mute or level knob and its step row, with a rail and screws per unit:RackPanel).Pad shape: square key (small radius, hard bottom edge), rubber pad (
border-radius: 30%, inset shadow), or round cap (50%).Panel material: flat plate, brushed metal (a
repeating-linear-gradientof two--surface-led mixes), or wood cheeks (thick side borders mixed from--orangeand--ink).LED colour role:
--info,--orangeor--up, which lights the playhead ring, the step lights and the readout.Transport layout: a strip above the grid, a deck below it, or a column beside it on wide screens.
Beat-group colours: four accents across the bar, two-tone by parity, or one tone with the lights doing the work.
Hardware cues, all from tokens: a bezel (2px solid var(--ink),
var(--r-card)), four screws, a printed name plate, a row of step lights over
the grid, a readout for the tempo, and knobs. A knob is a plain div with
role="slider": drag up to turn it, arrow keys step it, at least 56px across.
On a phone the grid runs eight pads a line, so every pad, button and knob stays
thumb-sized.
The parts above carry this face (FACE, Knob, Screws, Lights,
Transport, Knobs), and each sketch is one arrangement of them. A first build
picks an arrangement and the other axes; keep every colour a token mix.
— End —