@vibes.diy/prompts 14.3.249 → 14.3.250
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/generation-variety.js +1 -1
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/llms/backend.js +1 -0
- package/llms/backend.js.map +1 -1
- package/llms/blockly.js +1 -0
- package/llms/blockly.js.map +1 -1
- package/llms/blockly.md +2 -3
- package/llms/board-games.js +9 -4
- package/llms/board-games.js.map +1 -1
- package/llms/board-games.md +3 -153
- package/llms/callai.js +1 -0
- package/llms/callai.js.map +1 -1
- package/llms/callai.md +1 -1
- package/llms/canvas-theme-colors.d.ts +2 -0
- package/llms/canvas-theme-colors.js +7 -0
- package/llms/canvas-theme-colors.js.map +1 -0
- package/llms/canvas-theme-colors.md +70 -0
- package/llms/image-gen.js +1 -0
- package/llms/image-gen.js.map +1 -1
- package/llms/image-gen.md +1 -1
- package/llms/index.d.ts +20 -1
- package/llms/index.js +55 -0
- package/llms/index.js.map +1 -1
- package/llms/keepsake.d.ts +2 -0
- package/llms/keepsake.js +9 -0
- package/llms/keepsake.js.map +1 -0
- package/llms/keepsake.md +74 -0
- package/llms/live-rooms.d.ts +2 -0
- package/llms/live-rooms.js +28 -0
- package/llms/live-rooms.js.map +1 -0
- package/llms/live-rooms.md +288 -0
- package/llms/media-capture.d.ts +2 -0
- package/llms/media-capture.js +27 -0
- package/llms/media-capture.js.map +1 -0
- package/llms/media-capture.md +190 -0
- package/llms/mic-capture.d.ts +2 -0
- package/llms/mic-capture.js +7 -0
- package/llms/mic-capture.js.map +1 -0
- package/llms/mic-capture.md +76 -0
- package/llms/needs.d.ts +12 -0
- package/llms/needs.js +71 -0
- package/llms/needs.js.map +1 -0
- package/llms/p5.js +1 -0
- package/llms/p5.js.map +1 -1
- package/llms/p5.md +15 -69
- package/llms/photo-input.d.ts +2 -0
- package/llms/photo-input.js +7 -0
- package/llms/photo-input.js.map +1 -0
- package/llms/photo-input.md +141 -0
- package/llms/physics.js +1 -0
- package/llms/physics.js.map +1 -1
- package/llms/physics.md +7 -16
- package/llms/reskin.js +3 -8
- package/llms/reskin.js.map +1 -1
- package/llms/reskin.md +4 -72
- package/llms/richtext.md +2 -0
- package/llms/social-post.js +1 -0
- package/llms/social-post.js.map +1 -1
- package/llms/social-post.md +22 -4
- package/llms/sound-core.d.ts +2 -0
- package/llms/sound-core.js +7 -0
- package/llms/sound-core.js.map +1 -0
- package/llms/sound-core.md +131 -0
- package/llms/strudel.js +2 -0
- package/llms/strudel.js.map +1 -1
- package/llms/strudel.md +24 -25
- package/llms/surface-board.d.ts +2 -0
- package/llms/surface-board.js +8 -0
- package/llms/surface-board.js.map +1 -0
- package/llms/surface-board.md +140 -0
- package/llms/surface-play-area.d.ts +2 -0
- package/llms/surface-play-area.js +8 -0
- package/llms/surface-play-area.js.map +1 -0
- package/llms/surface-play-area.md +51 -0
- package/llms/surface-presence.d.ts +2 -0
- package/llms/surface-presence.js +9 -0
- package/llms/surface-presence.js.map +1 -0
- package/llms/surface-presence.md +118 -0
- package/llms/three-js.js +1 -1
- package/llms/three-js.js.map +1 -1
- package/llms/three-js.md +52 -18
- package/llms/touch-games.js +11 -11
- package/llms/touch-games.js.map +1 -1
- package/llms/touch-games.md +59 -354
- package/llms/types.d.ts +5 -0
- package/llms/ui-chat.js +2 -1
- package/llms/ui-chat.js.map +1 -1
- package/llms/ui-chat.md +25 -14
- package/llms/use-vibe.js +1 -0
- package/llms/use-vibe.js.map +1 -1
- package/llms/use-viewer.js +1 -0
- package/llms/use-viewer.js.map +1 -1
- package/llms/voxel.js +1 -0
- package/llms/voxel.js.map +1 -1
- package/llms/voxel.md +33 -109
- package/llms/web-audio.js +4 -21
- package/llms/web-audio.js.map +1 -1
- package/llms/web-audio.md +19 -951
- package/llms/web-music.d.ts +2 -0
- package/llms/web-music.js +8 -0
- package/llms/web-music.js.map +1 -0
- package/llms/web-music.md +895 -0
- package/llms/world-controls.d.ts +2 -0
- package/llms/world-controls.js +14 -0
- package/llms/world-controls.js.map +1 -0
- package/llms/world-controls.md +262 -0
- package/llms/worlds.js +2 -1
- package/llms/worlds.js.map +1 -1
- package/llms/worlds.md +5 -14
- package/package.json +5 -5
- package/prompts.js +5 -19
- package/prompts.js.map +1 -1
|
@@ -0,0 +1,895 @@
|
|
|
1
|
+
# Web music: master bus, echo with FX in the feedback loop, mic monitoring with a metronome, audio-clock timing, and a complete drum machine
|
|
2
|
+
|
|
3
|
+
Authoritative source: Issue #228 research threads — comments 3192681700, 3192696052, 3192806626.
|
|
4
|
+
|
|
5
|
+
> **This builds on the Web Audio doc above.** The context is the sound core's
|
|
6
|
+
> `unlockAudio()`, called first, synchronously, in the gesture; the core nodes and
|
|
7
|
+
> heavyweight engines that arrive by runtime import are taught there.
|
|
8
|
+
>
|
|
9
|
+
> **A drum machine, beat maker or step sequencer starts from §6** — a complete,
|
|
10
|
+
> runnable one with a synthesized kit, sixteen steps, tempo, swing, saturation
|
|
11
|
+
> and volume.
|
|
12
|
+
|
|
13
|
+
## 1) Master bus — every audio toy ships Saturation and Volume
|
|
14
|
+
|
|
15
|
+
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.
|
|
16
|
+
|
|
17
|
+
- Route every voice through one master `GainNode` and give the person a Volume control that sets its gain.
|
|
18
|
+
- Put one `WaveShaperNode` on the master bus and give the person a Saturation control that sets how hard it drives.
|
|
19
|
+
|
|
20
|
+
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.
|
|
21
|
+
|
|
22
|
+
```js
|
|
23
|
+
// Build once, beside the context (inside unlockAudio() or the engine's init).
|
|
24
|
+
function makeSaturationCurve(amount) {
|
|
25
|
+
// amount 0..1 → 0 is no curve at all (a true bypass; a straight-line curve would still
|
|
26
|
+
// clamp summed voices above 1.0), 1 is hard tanh drive.
|
|
27
|
+
if (amount === 0) return null;
|
|
28
|
+
const k = amount * 50;
|
|
29
|
+
const n = 1024;
|
|
30
|
+
const curve = new Float32Array(n);
|
|
31
|
+
for (let i = 0; i < n; i++) {
|
|
32
|
+
const x = (i / (n - 1)) * 2 - 1;
|
|
33
|
+
curve[i] = Math.tanh(k * x) / Math.tanh(k);
|
|
34
|
+
}
|
|
35
|
+
return curve;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const bus = audioCtx.createGain();
|
|
39
|
+
const saturation = audioCtx.createWaveShaper();
|
|
40
|
+
saturation.curve = makeSaturationCurve(0);
|
|
41
|
+
saturation.oversample = "4x";
|
|
42
|
+
const master = audioCtx.createGain();
|
|
43
|
+
master.gain.value = 0.8;
|
|
44
|
+
bus.connect(saturation).connect(master).connect(audioCtx.destination);
|
|
45
|
+
|
|
46
|
+
// Every voice lands on the bus, never on destination directly.
|
|
47
|
+
// voiceGain.connect(bus);
|
|
48
|
+
|
|
49
|
+
// The two global controls.
|
|
50
|
+
function setSaturation(amount) {
|
|
51
|
+
saturation.curve = makeSaturationCurve(amount);
|
|
52
|
+
}
|
|
53
|
+
function setVolume(value) {
|
|
54
|
+
master.gain.setTargetAtTime(value, audioCtx.currentTime, 0.02);
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
```jsx
|
|
59
|
+
import { Slider } from "@vibes.diy/ui/interactive";
|
|
60
|
+
|
|
61
|
+
<Slider label="Saturation" min={0} max={1} step={0.01} value={[drive]} onChange={([v]) => { setDrive(v); setSaturation(v); }} />
|
|
62
|
+
<Slider label="Volume" min={0} max={1} step={0.01} value={[volume]} onChange={([v]) => { setVolumeState(v); setVolume(v); }} />
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
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`.
|
|
66
|
+
|
|
67
|
+
## 2) Echo/Delay with Effects Inside the Feedback Loop
|
|
68
|
+
|
|
69
|
+
Graph (node names are exact):
|
|
70
|
+
|
|
71
|
+
- Dry: `source → dryGain:GainNode → destination`
|
|
72
|
+
- Wet: `source → delay:DelayNode → wetGain:GainNode → destination`
|
|
73
|
+
- Feedback loop with FX: `delay → filter:BiquadFilterNode → distortion:WaveShaperNode → reverb:ConvolverNode → feedbackGain:GainNode → delay`
|
|
74
|
+
|
|
75
|
+
Parameters to expose
|
|
76
|
+
|
|
77
|
+
- `delay.delayTime` (s), `feedbackGain.gain` (0–1, keep < 1.0)
|
|
78
|
+
- `filter.type`, `filter.frequency`
|
|
79
|
+
- `distortion.curve` (Float32Array)
|
|
80
|
+
- `convolver.buffer` (IR AudioBuffer)
|
|
81
|
+
- `wetGain.gain`, `dryGain.gain`
|
|
82
|
+
|
|
83
|
+
Notes: Prevent runaway by capping feedback below 1.0; `ConvolverNode` requires a loaded impulse response; zero-delay cycles are disallowed.
|
|
84
|
+
|
|
85
|
+
```js
|
|
86
|
+
const delay = audioCtx.createDelay(5.0);
|
|
87
|
+
const feedbackGain = audioCtx.createGain();
|
|
88
|
+
const filter = audioCtx.createBiquadFilter();
|
|
89
|
+
const distortion = audioCtx.createWaveShaper();
|
|
90
|
+
const reverb = audioCtx.createConvolver();
|
|
91
|
+
const wetGain = audioCtx.createGain();
|
|
92
|
+
const dryGain = audioCtx.createGain();
|
|
93
|
+
|
|
94
|
+
delay.delayTime.value = 0.35;
|
|
95
|
+
feedbackGain.gain.value = 0.5; // < 1.0
|
|
96
|
+
filter.type = "lowpass";
|
|
97
|
+
filter.frequency.value = 8000;
|
|
98
|
+
// distortion.curve = yourFloat32Curve;
|
|
99
|
+
// reverb.buffer = yourImpulseResponseAudioBuffer;
|
|
100
|
+
wetGain.gain.value = 0.4;
|
|
101
|
+
dryGain.gain.value = 1.0;
|
|
102
|
+
|
|
103
|
+
// Dry and wet
|
|
104
|
+
source.connect(dryGain).connect(audioCtx.destination);
|
|
105
|
+
source.connect(delay);
|
|
106
|
+
delay.connect(wetGain).connect(audioCtx.destination);
|
|
107
|
+
|
|
108
|
+
// Feedback with FX
|
|
109
|
+
delay.connect(filter);
|
|
110
|
+
filter.connect(distortion);
|
|
111
|
+
distortion.connect(reverb);
|
|
112
|
+
reverb.connect(feedbackGain);
|
|
113
|
+
feedbackGain.connect(delay);
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Helper (load IR):
|
|
117
|
+
|
|
118
|
+
```js
|
|
119
|
+
async function loadImpulseResponse(url) {
|
|
120
|
+
const res = await fetch(url, { mode: "cors" });
|
|
121
|
+
if (!res.ok) throw new Error(`Failed to fetch IR ${url}: ${res.status} ${res.statusText}`);
|
|
122
|
+
const ab = await res.arrayBuffer();
|
|
123
|
+
try {
|
|
124
|
+
return await audioCtx.decodeAudioData(ab);
|
|
125
|
+
} catch (err) {
|
|
126
|
+
console.error("decodeAudioData failed for IR", url, err);
|
|
127
|
+
throw err; // Surface decoding/CORS-related failures clearly
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## 3) Microphone Monitoring + Metronome Overlay
|
|
133
|
+
|
|
134
|
+
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.
|
|
135
|
+
|
|
136
|
+
Metronome: synthesize a short click (e.g., square/sine burst through a gain envelope). Schedule by audio clock at `AudioContext.currentTime` with lookahead.
|
|
137
|
+
|
|
138
|
+
Mix graph: `micGain + metronomeGain → master → destination`.
|
|
139
|
+
|
|
140
|
+
```js
|
|
141
|
+
const master = audioCtx.createGain();
|
|
142
|
+
master.connect(audioCtx.destination);
|
|
143
|
+
const micGain = audioCtx.createGain();
|
|
144
|
+
const metronomeGain = audioCtx.createGain();
|
|
145
|
+
micGain.connect(master);
|
|
146
|
+
metronomeGain.connect(master);
|
|
147
|
+
|
|
148
|
+
// From the Start tap, after unlockAudio(). A refusal comes back as { ok: false, reason }.
|
|
149
|
+
async function initMic() {
|
|
150
|
+
const mic = await openMic(MUSIC);
|
|
151
|
+
if (mic.ok) audioCtx.createMediaStreamSource(mic.stream).connect(micGain);
|
|
152
|
+
return mic;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function scheduleClick(atTime, downbeat = false) {
|
|
156
|
+
const osc = audioCtx.createOscillator();
|
|
157
|
+
const env = audioCtx.createGain();
|
|
158
|
+
osc.type = "square";
|
|
159
|
+
osc.frequency.setValueAtTime(downbeat ? 2000 : 1600, atTime);
|
|
160
|
+
env.gain.setValueAtTime(0.0001, atTime);
|
|
161
|
+
env.gain.exponentialRampToValueAtTime(1.0, atTime + 0.001);
|
|
162
|
+
env.gain.exponentialRampToValueAtTime(0.0001, atTime + 0.03);
|
|
163
|
+
osc.connect(env).connect(metronomeGain);
|
|
164
|
+
osc.start(atTime);
|
|
165
|
+
osc.stop(atTime + 0.05);
|
|
166
|
+
// Cleanup to avoid accumulating nodes during long sessions
|
|
167
|
+
osc.onended = () => {
|
|
168
|
+
try {
|
|
169
|
+
osc.disconnect();
|
|
170
|
+
} catch {}
|
|
171
|
+
try {
|
|
172
|
+
env.disconnect();
|
|
173
|
+
} catch {}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function startMetronome({ bpm = 120, beatsPerBar = 4 } = {}) {
|
|
178
|
+
const spb = 60 / bpm; // seconds per beat
|
|
179
|
+
let next = audioCtx.currentTime + 0.1;
|
|
180
|
+
let beat = 0;
|
|
181
|
+
const lookaheadMs = 25,
|
|
182
|
+
ahead = 0.2;
|
|
183
|
+
const id = setInterval(() => {
|
|
184
|
+
while (next < audioCtx.currentTime + ahead) {
|
|
185
|
+
scheduleClick(next, beat % beatsPerBar === 0);
|
|
186
|
+
next += spb;
|
|
187
|
+
beat = (beat + 1) % beatsPerBar;
|
|
188
|
+
}
|
|
189
|
+
}, lookaheadMs);
|
|
190
|
+
return () => clearInterval(id);
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
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.
|
|
195
|
+
|
|
196
|
+
## 4) Time Synchronization and Scheduling Model
|
|
197
|
+
|
|
198
|
+
Clocks/time domains
|
|
199
|
+
|
|
200
|
+
- Master: `AudioContext.currentTime` — sample-accurate; schedule everything on this timeline.
|
|
201
|
+
- UI/high-res: `performance.now()` — for UI timers and Web MIDI timestamps.
|
|
202
|
+
- Mapping: capture `(tPerf0 = performance.now(), tAudio0 = audioCtx.currentTime)`, convert MIDI/perf timestamps with `tAudio = tAudio0 + (timeStamp - tPerf0)/1000`.
|
|
203
|
+
- Hints: `audioCtx.baseLatency`, `audioCtx.getOutputTimestamp?.()` — estimate DAC/output delay if aligning to “heard” time.
|
|
204
|
+
|
|
205
|
+
Scheduling primitives
|
|
206
|
+
|
|
207
|
+
- `AudioBufferSourceNode.start(when, offset?, duration?)` for one-shots/loops.
|
|
208
|
+
- `AudioParam` automation (`setValueAtTime`, `linearRampToValueAtTime`, `setTargetAtTime`, `setValueCurveAtTime`).
|
|
209
|
+
- Avoid `requestAnimationFrame`/`setTimeout` for timing; use an AudioWorklet for custom DSP/tight jitter when needed.
|
|
210
|
+
|
|
211
|
+
Tempo transport and lookahead
|
|
212
|
+
|
|
213
|
+
- Tempo mapping: `secondsPerBeat = 60 / bpm`; compute bars:beats:ticks → seconds on the audio clock (choose PPQ, e.g., 480/960).
|
|
214
|
+
- Lookahead window: maintain ~50–200 ms rolling schedule; enqueue with absolute `when` times in audio seconds.
|
|
215
|
+
|
|
216
|
+
Multi‑channel sample playback
|
|
217
|
+
|
|
218
|
+
- Pre‑decode all samples; never decode on hit.
|
|
219
|
+
- Per hit: create a fresh `AudioBufferSourceNode` and call `.start(when)`.
|
|
220
|
+
- For phase‑aligned layers (kick+clap, etc.), schedule all sources with the same `when` to guarantee sample‑accurate overlap.
|
|
221
|
+
- Routing: per‑track `GainNode`/optional FX → master bus; allow overlapping retriggers; compute flams as small `when` offsets.
|
|
222
|
+
- Pattern changes: compute the next bar boundary on the audio clock and enqueue new pattern hits relative to that time.
|
|
223
|
+
|
|
224
|
+
MIDI synth playback
|
|
225
|
+
|
|
226
|
+
- Live input: map `MIDIMessageEvent.timeStamp` (perf.now domain) → audio clock as above; buffer a short lookahead (5–20 ms) to reduce jitter.
|
|
227
|
+
- SMF playback: convert PPQ ticks using the tempo map; schedule noteOn/noteOff separately; sustain (CC64) defers noteOff until pedal release.
|
|
228
|
+
- Voice management: one voice per active note; allow overlapping envelopes; define voice‑steal policy if a polyphony cap is hit.
|
|
229
|
+
|
|
230
|
+
External sync and drift
|
|
231
|
+
|
|
232
|
+
- 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.
|
|
233
|
+
|
|
234
|
+
## 5) File layout — audio apps split, proactively
|
|
235
|
+
|
|
236
|
+
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`).
|
|
237
|
+
|
|
238
|
+
The shape that works (filenames illustrative — split by responsibility, matched to the app's actual surfaces, not by count):
|
|
239
|
+
|
|
240
|
+
- `lib/audio-engine.js` — everything that touches `AudioContext`: the `unlockAudio()` 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.
|
|
241
|
+
- `components/Keyboard.jsx` (or `StepGrid.jsx`, `Pads.jsx`) — the playable surface; calls engine functions from `pointerdown`-family handlers.
|
|
242
|
+
- `components/TransportControls.jsx`, `components/PresetList.jsx` — parameter knobs/sliders and preset browsing; presets live in the database, the engine consumes plain parameter objects.
|
|
243
|
+
- `App.jsx` — layout, styling, database wiring; imports the above (`import { createEngine } from "./lib/audio-engine.js"`).
|
|
244
|
+
|
|
245
|
+
## 6) A complete drum machine — the shell every beat vibe starts from
|
|
246
|
+
|
|
247
|
+
Build the first version of any beat app (a drum machine, beat maker, step
|
|
248
|
+
sequencer or groovebox) from this section: the engine as written, and an
|
|
249
|
+
instrument face whose picks you choose (§ "Make it yours" below). The
|
|
250
|
+
`data-instrument` panel is how a drum machine looks from its very first build,
|
|
251
|
+
under any look, layout or skin the turn also carries. The `App.jsx` below
|
|
252
|
+
holds the parts every arrangement shares, followed by three short arrangement
|
|
253
|
+
sketches: pick one and write the app around it.
|
|
254
|
+
|
|
255
|
+
This is a two-file kit: a synthesized four-voice kit (kick,
|
|
256
|
+
snare, closed and open hat), a sixteen-step sequencer, tempo and swing, and
|
|
257
|
+
global saturation and volume on the master bus. No samples, no downloads —
|
|
258
|
+
every sound is built from oscillators and noise, so it plays the moment the
|
|
259
|
+
person taps. Start here for any drum machine, beat maker, step sequencer or groovebox and grow
|
|
260
|
+
it: more voices, more steps, accents, pattern banks.
|
|
261
|
+
|
|
262
|
+
Why it sounds good, in four moves:
|
|
263
|
+
|
|
264
|
+
- **Kick** — a sine that sweeps 150 Hz → 55 Hz in 50 ms, then settles to 45 Hz:
|
|
265
|
+
the sweep is the punch, the tail is the boom. A few milliseconds of
|
|
266
|
+
band-passed noise on top is the beater, so the kick still reads on phone
|
|
267
|
+
speakers that cannot reproduce 45 Hz.
|
|
268
|
+
- **Snare** — two tuned triangle "shell" tones under high-passed noise with a
|
|
269
|
+
presence lift at 5 kHz for the wires.
|
|
270
|
+
- **Hats** — the 808 recipe: six square waves at inharmonic ratios of 40 Hz,
|
|
271
|
+
band-passed at 10 kHz and high-passed at 7 kHz. A closed hat chokes a ringing
|
|
272
|
+
open hat through the open hat's own gate gain, like the real machine.
|
|
273
|
+
- **Master bus** — voices → bus (headroom) → drive gain → `tanh` WaveShaper
|
|
274
|
+
(4× oversampled, so the new harmonics do not alias into fizz) → makeup gain →
|
|
275
|
+
volume → a fast `DynamicsCompressor` as a limiter. The makeup gain falls as
|
|
276
|
+
the drive rises, so Saturation changes the colour, not the loudness; Volume
|
|
277
|
+
is squared so the slider feels even.
|
|
278
|
+
|
|
279
|
+
The engine is a plain module (§5): the sound core's gate, the lookahead scheduler
|
|
280
|
+
from §4, and a `playhead()` the interface polls each animation frame, so the
|
|
281
|
+
lit step follows what is reaching the speakers rather than the timer. The steps
|
|
282
|
+
are `StepGrid` rows of `Pad`s from `@vibes.diy/ui/interactive`: square pads
|
|
283
|
+
in beats of four, a light on the playing step, sixteen across on a laptop and
|
|
284
|
+
eight a line on a phone. A pad is an instrument's square, so the grid reads as a
|
|
285
|
+
drum machine, never as a column of settings toggles; a single `Pad` is the
|
|
286
|
+
finger-drumming pad of an MPC-style kit or a launch cell. The
|
|
287
|
+
interface calls `getDrums()` synchronously at the top of every tap handler —
|
|
288
|
+
Play, and each step — which is what unlocks sound on iOS.
|
|
289
|
+
|
|
290
|
+
### `lib/drum-engine.js`
|
|
291
|
+
```js
|
|
292
|
+
// Everything that touches AudioContext lives here — no React, so a re-render never rebuilds the graph.
|
|
293
|
+
export const STEPS = 16;
|
|
294
|
+
export const TRACKS = [
|
|
295
|
+
{ id: "kick", label: "Kick" },
|
|
296
|
+
{ id: "snare", label: "Snare" },
|
|
297
|
+
{ id: "closed", label: "Closed hat" },
|
|
298
|
+
{ id: "open", label: "Open hat" },
|
|
299
|
+
];
|
|
300
|
+
|
|
301
|
+
let audioCtx;
|
|
302
|
+
let drums;
|
|
303
|
+
|
|
304
|
+
// The sound core's gate: synchronous, inside the tap, with one real (silent) sound.
|
|
305
|
+
function unlockAudio() {
|
|
306
|
+
audioCtx ||= new (window.AudioContext || window.webkitAudioContext)();
|
|
307
|
+
if (audioCtx.state !== "running") {
|
|
308
|
+
audioCtx.resume();
|
|
309
|
+
const osc = audioCtx.createOscillator();
|
|
310
|
+
const gain = audioCtx.createGain();
|
|
311
|
+
gain.gain.value = 0.0001;
|
|
312
|
+
osc.connect(gain).connect(audioCtx.destination);
|
|
313
|
+
osc.start();
|
|
314
|
+
osc.stop(audioCtx.currentTime + 0.01);
|
|
315
|
+
}
|
|
316
|
+
return audioCtx;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// Call from a tap handler, synchronously: unlocks audio and builds the one engine on that context.
|
|
320
|
+
export function getDrums() {
|
|
321
|
+
const ctx = unlockAudio();
|
|
322
|
+
drums ||= createDrums(ctx);
|
|
323
|
+
return drums;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function createDrums(ctx) {
|
|
327
|
+
const settings = { pattern: {}, bpm: 112, swing: 0, drive: 0.3, volume: 0.8 };
|
|
328
|
+
|
|
329
|
+
// Master chain: voices → bus → drive → tanh shaper → makeup → volume → limiter → speakers.
|
|
330
|
+
const bus = ctx.createGain();
|
|
331
|
+
const drive = ctx.createGain();
|
|
332
|
+
const shaper = ctx.createWaveShaper();
|
|
333
|
+
const makeup = ctx.createGain();
|
|
334
|
+
const volume = ctx.createGain();
|
|
335
|
+
const limiter = ctx.createDynamicsCompressor();
|
|
336
|
+
bus.gain.value = 0.7; // headroom: a kick and a hat on the same step stay under full scale
|
|
337
|
+
shaper.curve = tanhCurve(MAX_DRIVE);
|
|
338
|
+
shaper.oversample = "4x"; // keeps the new harmonics from folding back down as fizz
|
|
339
|
+
limiter.threshold.value = -3;
|
|
340
|
+
limiter.knee.value = 0;
|
|
341
|
+
limiter.ratio.value = 20;
|
|
342
|
+
limiter.attack.value = 0.002;
|
|
343
|
+
limiter.release.value = 0.1;
|
|
344
|
+
bus.connect(drive).connect(shaper).connect(makeup).connect(volume).connect(limiter).connect(ctx.destination);
|
|
345
|
+
|
|
346
|
+
const noise = noiseBuffer(ctx);
|
|
347
|
+
const live = new Set(); // every scheduled source and its start time, so Stop can cancel the future
|
|
348
|
+
let openChoke = null; // the ringing open hat's gate — a closed hat shuts it, like the real machine
|
|
349
|
+
|
|
350
|
+
function chokeOpen(at) {
|
|
351
|
+
openChoke?.gain.setTargetAtTime(0, at, 0.006);
|
|
352
|
+
openChoke = null;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function play(source, at, end, nodes = []) {
|
|
356
|
+
const entry = { source, at };
|
|
357
|
+
live.add(entry);
|
|
358
|
+
source.onended = () => {
|
|
359
|
+
live.delete(entry);
|
|
360
|
+
source.disconnect();
|
|
361
|
+
for (const node of nodes) node.disconnect();
|
|
362
|
+
};
|
|
363
|
+
source.start(at);
|
|
364
|
+
source.stop(end);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// A percussive envelope: 2 ms attack, exponential decay to silence.
|
|
368
|
+
function envelope(at, peak, decay, out = bus) {
|
|
369
|
+
const amp = ctx.createGain();
|
|
370
|
+
amp.gain.setValueAtTime(0.0001, at);
|
|
371
|
+
amp.gain.exponentialRampToValueAtTime(peak, at + 0.002);
|
|
372
|
+
amp.gain.exponentialRampToValueAtTime(0.0001, at + decay);
|
|
373
|
+
amp.connect(out);
|
|
374
|
+
return amp;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function filter(type, frequency, q = 0.7) {
|
|
378
|
+
const node = ctx.createBiquadFilter();
|
|
379
|
+
node.type = type;
|
|
380
|
+
node.frequency.value = frequency;
|
|
381
|
+
node.Q.value = q;
|
|
382
|
+
return node;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// 808-style metal: six square waves at inharmonic ratios, band-passed high.
|
|
386
|
+
function hat(at, decay, peak, out) {
|
|
387
|
+
const band = filter("bandpass", 10000);
|
|
388
|
+
const high = filter("highpass", 7000);
|
|
389
|
+
const amp = envelope(at, peak, decay, out);
|
|
390
|
+
band.connect(high).connect(amp);
|
|
391
|
+
[2, 3, 4.16, 5.43, 6.79, 8.21].forEach((ratio, i) => {
|
|
392
|
+
const osc = ctx.createOscillator();
|
|
393
|
+
osc.type = "square";
|
|
394
|
+
osc.frequency.value = 40 * ratio;
|
|
395
|
+
osc.connect(band);
|
|
396
|
+
play(osc, at, at + decay + 0.02, i === 0 ? [band, high, amp] : []);
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const voices = {
|
|
401
|
+
kick(at) {
|
|
402
|
+
// A sine that drops from 150 Hz to 45 Hz: the pitch sweep is the punch, the tail is the boom.
|
|
403
|
+
const body = ctx.createOscillator();
|
|
404
|
+
body.frequency.setValueAtTime(150, at);
|
|
405
|
+
body.frequency.exponentialRampToValueAtTime(55, at + 0.05);
|
|
406
|
+
body.frequency.exponentialRampToValueAtTime(45, at + 0.4);
|
|
407
|
+
const amp = envelope(at, 1, 0.5);
|
|
408
|
+
body.connect(amp);
|
|
409
|
+
play(body, at, at + 0.55, [amp]);
|
|
410
|
+
// The beater: a few ms of filtered noise, so the kick still reads on phone speakers.
|
|
411
|
+
const click = ctx.createBufferSource();
|
|
412
|
+
click.buffer = noise;
|
|
413
|
+
const tone = filter("bandpass", 3500, 0.8);
|
|
414
|
+
const clickAmp = envelope(at, 0.3, 0.012);
|
|
415
|
+
click.connect(tone).connect(clickAmp);
|
|
416
|
+
play(click, at, at + 0.03, [tone, clickAmp]);
|
|
417
|
+
},
|
|
418
|
+
snare(at) {
|
|
419
|
+
// Two tuned shell tones under a bright burst of noise for the wires.
|
|
420
|
+
for (const [freq, level] of [[185, 0.45], [330, 0.25]]) {
|
|
421
|
+
const shell = ctx.createOscillator();
|
|
422
|
+
shell.type = "triangle";
|
|
423
|
+
shell.frequency.setValueAtTime(freq, at);
|
|
424
|
+
shell.frequency.exponentialRampToValueAtTime(freq * 0.85, at + 0.1);
|
|
425
|
+
const amp = envelope(at, level, 0.14);
|
|
426
|
+
shell.connect(amp);
|
|
427
|
+
play(shell, at, at + 0.16, [amp]);
|
|
428
|
+
}
|
|
429
|
+
const wires = ctx.createBufferSource();
|
|
430
|
+
wires.buffer = noise;
|
|
431
|
+
const high = filter("highpass", 1500);
|
|
432
|
+
const air = filter("peaking", 5000);
|
|
433
|
+
air.gain.value = 6;
|
|
434
|
+
const amp = envelope(at, 0.6, 0.22);
|
|
435
|
+
wires.connect(high).connect(air).connect(amp);
|
|
436
|
+
play(wires, at, at + 0.25, [high, air, amp]);
|
|
437
|
+
},
|
|
438
|
+
closed(at) {
|
|
439
|
+
chokeOpen(at);
|
|
440
|
+
hat(at, 0.06, 0.32, bus);
|
|
441
|
+
},
|
|
442
|
+
open(at) {
|
|
443
|
+
chokeOpen(at); // one open hat at a time, so the next closed hat always silences it
|
|
444
|
+
openChoke = ctx.createGain();
|
|
445
|
+
openChoke.connect(bus);
|
|
446
|
+
hat(at, 0.45, 0.24, openChoke);
|
|
447
|
+
},
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
// The scheduler: a 25 ms timer tops up 120 ms of sound ahead of the audio clock (§4).
|
|
451
|
+
const LOOKAHEAD = 0.12;
|
|
452
|
+
let timer = 0;
|
|
453
|
+
let step = 0;
|
|
454
|
+
let gridTime = 0;
|
|
455
|
+
let lit = -1;
|
|
456
|
+
const lights = []; // { step, at }: the playhead follows the sound, not the timer
|
|
457
|
+
|
|
458
|
+
function tick() {
|
|
459
|
+
const sixteenth = 60 / settings.bpm / 4;
|
|
460
|
+
// A throttled background tab can fall far behind the audio clock: skip the missed steps
|
|
461
|
+
// (keeping the beat's phase) instead of scheduling a burst of hits in the past.
|
|
462
|
+
if (gridTime < ctx.currentTime) {
|
|
463
|
+
const missed = Math.ceil((ctx.currentTime - gridTime) / sixteenth);
|
|
464
|
+
gridTime += missed * sixteenth;
|
|
465
|
+
step = (step + missed) % STEPS;
|
|
466
|
+
}
|
|
467
|
+
while (gridTime < ctx.currentTime + LOOKAHEAD) {
|
|
468
|
+
// Swing pushes every off-beat sixteenth late; 1 is a full triplet shuffle.
|
|
469
|
+
const at = gridTime + (step % 2 ? (settings.swing * sixteenth) / 3 : 0);
|
|
470
|
+
for (const { id } of TRACKS) if (settings.pattern[id]?.[step]) voices[id](at);
|
|
471
|
+
lights.push({ step, at });
|
|
472
|
+
gridTime += sixteenth;
|
|
473
|
+
step = (step + 1) % STEPS;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function update(next) {
|
|
478
|
+
Object.assign(settings, next);
|
|
479
|
+
const now = ctx.currentTime;
|
|
480
|
+
// Drive 0 is warm, 1 is crunchy. Makeup gain keeps loudness level as the drive rises,
|
|
481
|
+
// so the slider changes the colour, not the volume.
|
|
482
|
+
const gain = 1 + settings.drive * (MAX_DRIVE - 1);
|
|
483
|
+
drive.gain.setTargetAtTime(gain / MAX_DRIVE, now, 0.02);
|
|
484
|
+
makeup.gain.setTargetAtTime(1.3 / Math.sqrt(gain), now, 0.02);
|
|
485
|
+
volume.gain.setTargetAtTime(settings.volume ** 2, now, 0.02); // squared, so the slider feels even
|
|
486
|
+
}
|
|
487
|
+
update({});
|
|
488
|
+
|
|
489
|
+
return {
|
|
490
|
+
update,
|
|
491
|
+
start() {
|
|
492
|
+
if (timer) return;
|
|
493
|
+
step = 0;
|
|
494
|
+
gridTime = ctx.currentTime + 0.05;
|
|
495
|
+
tick();
|
|
496
|
+
timer = setInterval(tick, 25);
|
|
497
|
+
},
|
|
498
|
+
stop() {
|
|
499
|
+
clearInterval(timer);
|
|
500
|
+
timer = 0;
|
|
501
|
+
lights.length = 0;
|
|
502
|
+
lit = -1;
|
|
503
|
+
// Cancel every hit that is scheduled but not yet sounding; ringing tails finish on their own.
|
|
504
|
+
for (const entry of live) if (entry.at > ctx.currentTime) entry.source.stop();
|
|
505
|
+
},
|
|
506
|
+
// Audition one sound now — a tap on a step while stopped.
|
|
507
|
+
hit(id) {
|
|
508
|
+
voices[id](ctx.currentTime + 0.005);
|
|
509
|
+
},
|
|
510
|
+
// The newest step whose sound has reached the speakers; poll it from requestAnimationFrame.
|
|
511
|
+
playhead() {
|
|
512
|
+
// currentTime is what the engine has rendered; subtract the output latency for what is heard
|
|
513
|
+
// (it matters on Bluetooth headphones).
|
|
514
|
+
const heard = ctx.currentTime - (ctx.outputLatency || ctx.baseLatency || 0);
|
|
515
|
+
while (lights.length && lights[0].at <= heard) lit = lights.shift().step;
|
|
516
|
+
return lit;
|
|
517
|
+
},
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const MAX_DRIVE = 10;
|
|
522
|
+
|
|
523
|
+
// tanh(MAX_DRIVE·x) across the shaper's −1…1 input; the drive gain picks how far up the curve we go.
|
|
524
|
+
function tanhCurve(k) {
|
|
525
|
+
const curve = new Float32Array(4096);
|
|
526
|
+
for (let i = 0; i < curve.length; i++) curve[i] = Math.tanh(k * ((i / (curve.length - 1)) * 2 - 1));
|
|
527
|
+
return curve;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function noiseBuffer(ctx) {
|
|
531
|
+
const buffer = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);
|
|
532
|
+
const data = buffer.getChannelData(0);
|
|
533
|
+
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
|
|
534
|
+
return buffer;
|
|
535
|
+
}
|
|
536
|
+
```
|
|
537
|
+
|
|
538
|
+
A tap on a step toggles it, and while stopped it plays that sound so the
|
|
539
|
+
person hears what they placed. Every knob writes through to the engine, and
|
|
540
|
+
the scheduler reads the settings on its next step, so edits land in time
|
|
541
|
+
without a restart. Grooves save to the database as one document each; the
|
|
542
|
+
save button waits on `can.create`, the same verdict the server enforces.
|
|
543
|
+
|
|
544
|
+
### `App.jsx`
|
|
545
|
+
```jsx
|
|
546
|
+
// The parts every arrangement shares. `App` composes them with one of the three arrangements below.
|
|
547
|
+
import React, { useEffect, useRef, useState } from "react";
|
|
548
|
+
import { Button, Row, Spacer, Stack } from "@vibes.diy/ui";
|
|
549
|
+
import { StepGrid } from "@vibes.diy/ui/interactive";
|
|
550
|
+
import { STEPS, TRACKS, getDrums } from "./lib/drum-engine.js";
|
|
551
|
+
|
|
552
|
+
const START = {
|
|
553
|
+
kick: [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
|
|
554
|
+
snare: [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
|
|
555
|
+
closed: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0],
|
|
556
|
+
open: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
|
|
557
|
+
};
|
|
558
|
+
|
|
559
|
+
const FACE = `
|
|
560
|
+
/* picks: arrangement = … · pad = … · panel = … · led = … · transport = … (name yours; this sheet's defaults are square key, brushed, --info) */
|
|
561
|
+
[data-instrument] {
|
|
562
|
+
--panel: color-mix(in oklab, var(--surface) 80%, var(--ink));
|
|
563
|
+
--well: color-mix(in oklab, var(--surface) 75%, var(--ink));
|
|
564
|
+
--screen: color-mix(in oklab, var(--surface) 88%, var(--ink));
|
|
565
|
+
--led: var(--info);
|
|
566
|
+
--pad-off: color-mix(in oklab, var(--surface) 90%, var(--ink));
|
|
567
|
+
position: relative; display: grid; gap: var(--s3); padding: var(--s5) var(--s3) var(--s3);
|
|
568
|
+
border: 2px solid var(--ink); border-radius: var(--r-card); color: var(--ink);
|
|
569
|
+
background: repeating-linear-gradient(90deg, var(--panel) 0 2px, color-mix(in oklab, var(--panel) 92%, var(--surface)) 2px 4px);
|
|
570
|
+
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);
|
|
571
|
+
}
|
|
572
|
+
[data-instrument] .ix-screw { position: absolute; width: 10px; height: 10px; border-radius: 50%; border: 1px solid var(--ink);
|
|
573
|
+
background: radial-gradient(circle at 35% 35%, var(--surface), var(--well)); }
|
|
574
|
+
[data-instrument] .ix-screw--tl { top: 8px; left: 8px; } [data-instrument] .ix-screw--tr { top: 8px; right: 8px; }
|
|
575
|
+
[data-instrument] .ix-screw--bl { bottom: 8px; left: 8px; } [data-instrument] .ix-screw--br { bottom: 8px; right: 8px; }
|
|
576
|
+
[data-instrument] .ix-plate { justify-self: start; padding: 4px 10px; border: 1px solid var(--ink); border-radius: var(--r-control);
|
|
577
|
+
background: var(--surface); font: 700 12px/1.3 var(--font-family); letter-spacing: .16em; text-transform: uppercase; }
|
|
578
|
+
[data-instrument] .ix-label { font-size: 11px; letter-spacing: .14em; text-transform: uppercase; color: color-mix(in oklab, var(--ink) 75%, var(--panel)); }
|
|
579
|
+
[data-instrument] .ix-well { display: grid; gap: var(--s2); padding: var(--s2); border-radius: var(--r-control); background: var(--well);
|
|
580
|
+
box-shadow: inset 0 2px 5px color-mix(in oklab, var(--ink) 45%, transparent); }
|
|
581
|
+
[data-instrument] .ix-lcd { padding: 4px 10px; border-radius: 4px; border: 1px solid var(--ink); background: var(--screen);
|
|
582
|
+
box-shadow: inset 0 2px 4px color-mix(in oklab, var(--ink) 35%, transparent); font: 700 18px/1.2 ui-monospace, monospace;
|
|
583
|
+
font-variant-numeric: tabular-nums; color: color-mix(in oklab, var(--ink) 80%, var(--led));
|
|
584
|
+
text-shadow: 0 0 6px color-mix(in oklab, var(--led) 50%, transparent); }
|
|
585
|
+
[data-instrument] .ix-lights { display: grid; grid-template-columns: repeat(16, 1fr); gap: 4px; }
|
|
586
|
+
[data-instrument] .ix-light { height: 6px; border-radius: 3px; background: color-mix(in oklab, var(--led) 18%, var(--well)); }
|
|
587
|
+
[data-instrument] .ix-light[data-on] { background: var(--led); box-shadow: 0 0 8px var(--led); }
|
|
588
|
+
[data-instrument] .ui-pad { border: 1px solid var(--ink); border-radius: 4px; box-shadow: 0 3px 0 var(--ink); }
|
|
589
|
+
[data-instrument] .ui-pad[data-state="off"] { background: var(--pad-off); }
|
|
590
|
+
[data-instrument] .ui-pad[data-state="on"][data-group="0"] { background: var(--purple); }
|
|
591
|
+
[data-instrument] .ui-pad[data-state="on"][data-group="1"] { background: var(--orange); }
|
|
592
|
+
[data-instrument] .ui-pad[data-state="on"][data-group="2"] { background: var(--up); }
|
|
593
|
+
[data-instrument] .ui-pad[data-state="on"][data-group="3"] { background: color-mix(in oklab, var(--purple) 50%, var(--orange)); }
|
|
594
|
+
[data-instrument] .ui-pad[data-state="on"] .ui-pad__led { background: var(--on-accent); box-shadow: 0 0 8px var(--on-accent); }
|
|
595
|
+
[data-instrument] .ui-pad__ring { box-shadow: inset 0 0 0 3px var(--led), 0 0 10px var(--led); }
|
|
596
|
+
[data-instrument] .ix-knob { display: grid; justify-items: center; gap: 4px; }
|
|
597
|
+
[data-instrument] .ix-knob__cap { position: relative; width: 56px; height: 56px; border-radius: 50%; border: 2px solid var(--ink);
|
|
598
|
+
touch-action: none; cursor: ns-resize; box-shadow: 0 3px 0 var(--ink);
|
|
599
|
+
background: radial-gradient(circle at 40% 35%, color-mix(in oklab, var(--surface) 92%, var(--ink)), var(--well) 72%);
|
|
600
|
+
transform: rotate(calc(-135deg + var(--turn) * 270deg)); }
|
|
601
|
+
[data-instrument] .ix-knob__cap::after { content: ""; position: absolute; left: calc(50% - 2px); top: 5px; width: 4px; height: 16px;
|
|
602
|
+
border-radius: 2px; background: var(--led); box-shadow: 0 0 6px var(--led); }
|
|
603
|
+
[data-instrument] .ix-knob__cap:focus-visible { outline: 3px solid var(--ink); outline-offset: 3px; }
|
|
604
|
+
/* arrangement helpers: a pad grid lays one voice's steps four by four; a rack stacks voice units */
|
|
605
|
+
[data-instrument] .ix-grid4 .ui-stepgrid { --ui-steps: 4; --ui-steps-narrow: 4; }
|
|
606
|
+
[data-instrument] .ix-voices { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--s2); }
|
|
607
|
+
[data-instrument] .ix-unit { position: relative; display: grid; gap: var(--s2); padding: var(--s3); border: 1px solid var(--ink);
|
|
608
|
+
border-radius: var(--r-control); background: var(--well); }
|
|
609
|
+
`;
|
|
610
|
+
|
|
611
|
+
// A knob turns: drag up to raise it, arrow keys step it. Its value shows on a small readout.
|
|
612
|
+
function Knob({ label, value, min, max, shown, onChange }) {
|
|
613
|
+
const drag = useRef(null);
|
|
614
|
+
const clamp = (v) => Math.min(max, Math.max(min, Math.round(v)));
|
|
615
|
+
const turn = { "--turn": (value - min) / (max - min) };
|
|
616
|
+
return (
|
|
617
|
+
<div className="ix-knob">
|
|
618
|
+
<div
|
|
619
|
+
role="slider"
|
|
620
|
+
tabIndex={0}
|
|
621
|
+
aria-label={label}
|
|
622
|
+
aria-valuemin={min}
|
|
623
|
+
aria-valuemax={max}
|
|
624
|
+
aria-valuenow={value}
|
|
625
|
+
className="ix-knob__cap"
|
|
626
|
+
style={turn}
|
|
627
|
+
onPointerDown={(e) => {
|
|
628
|
+
e.currentTarget.setPointerCapture(e.pointerId);
|
|
629
|
+
drag.current = { y: e.clientY, v: value };
|
|
630
|
+
}}
|
|
631
|
+
onPointerMove={(e) => drag.current && onChange(clamp(drag.current.v + ((drag.current.y - e.clientY) / 160) * (max - min)))}
|
|
632
|
+
onPointerUp={() => (drag.current = null)}
|
|
633
|
+
onPointerCancel={() => (drag.current = null)}
|
|
634
|
+
onKeyDown={(e) => {
|
|
635
|
+
const d = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1 }[e.key];
|
|
636
|
+
if (d) {
|
|
637
|
+
e.preventDefault();
|
|
638
|
+
onChange(clamp(value + d));
|
|
639
|
+
}
|
|
640
|
+
}}
|
|
641
|
+
/>
|
|
642
|
+
<span className="ix-label">{label}</span>
|
|
643
|
+
<span className="ix-lcd">{shown}</span>
|
|
644
|
+
</div>
|
|
645
|
+
);
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// The engine wiring every arrangement shares: state, the iOS unlock, and a playhead that follows the sound.
|
|
649
|
+
function useDrumMachine() {
|
|
650
|
+
const [grid, setGrid] = useState(START);
|
|
651
|
+
const [bpm, setBpm] = useState(112);
|
|
652
|
+
const [swing, setSwing] = useState(0);
|
|
653
|
+
const [drive, setDrive] = useState(30);
|
|
654
|
+
const [volume, setVolume] = useState(80);
|
|
655
|
+
const [playing, setPlaying] = useState(false);
|
|
656
|
+
const [step, setStep] = useState(-1);
|
|
657
|
+
const drumsRef = useRef(null);
|
|
658
|
+
const settings = { pattern: grid, bpm, swing: swing / 100, drive: drive / 100, volume: volume / 100 };
|
|
659
|
+
|
|
660
|
+
useEffect(() => {
|
|
661
|
+
drumsRef.current?.update(settings);
|
|
662
|
+
}, [grid, bpm, swing, drive, volume]);
|
|
663
|
+
useEffect(() => () => drumsRef.current?.stop(), []);
|
|
664
|
+
useEffect(() => {
|
|
665
|
+
if (!playing) return;
|
|
666
|
+
let raf = 0;
|
|
667
|
+
const frame = () => {
|
|
668
|
+
setStep(drumsRef.current.playhead());
|
|
669
|
+
raf = requestAnimationFrame(frame);
|
|
670
|
+
};
|
|
671
|
+
raf = requestAnimationFrame(frame);
|
|
672
|
+
return () => cancelAnimationFrame(raf);
|
|
673
|
+
}, [playing]);
|
|
674
|
+
|
|
675
|
+
// Called synchronously at the top of every tap handler: that is what unlocks audio on iOS.
|
|
676
|
+
function drums() {
|
|
677
|
+
const engine = getDrums();
|
|
678
|
+
if (!drumsRef.current) engine.update(settings);
|
|
679
|
+
drumsRef.current = engine;
|
|
680
|
+
return engine;
|
|
681
|
+
}
|
|
682
|
+
function togglePlay() {
|
|
683
|
+
const engine = drums();
|
|
684
|
+
if (playing) {
|
|
685
|
+
engine.stop();
|
|
686
|
+
setStep(-1);
|
|
687
|
+
} else engine.start();
|
|
688
|
+
setPlaying(!playing);
|
|
689
|
+
}
|
|
690
|
+
function toggleStep(track, i) {
|
|
691
|
+
const engine = drums();
|
|
692
|
+
const on = !grid[track][i];
|
|
693
|
+
setGrid({ ...grid, [track]: grid[track].map((v, j) => (j === i ? (on ? 1 : 0) : v)) });
|
|
694
|
+
if (on && !playing) engine.hit(track); // hear the sound you just placed
|
|
695
|
+
}
|
|
696
|
+
const hit = (track) => drums().hit(track);
|
|
697
|
+
const clear = () => setGrid(Object.fromEntries(TRACKS.map(({ id }) => [id, Array(STEPS).fill(0)])));
|
|
698
|
+
return { grid, setGrid, bpm, setBpm, swing, setSwing, drive, setDrive, volume, setVolume, playing, step, togglePlay, toggleStep, hit, clear };
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// Four corner screws; a rack unit carries its own set.
|
|
702
|
+
function Screws() {
|
|
703
|
+
return ["tl", "tr", "bl", "br"].map((at) => <span key={at} className={`ix-screw ix-screw--${at}`} aria-hidden="true" />);
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// The panel itself: bezel, sheet, screws and a printed name plate.
|
|
707
|
+
function Panel({ label, plate, children }) {
|
|
708
|
+
return (
|
|
709
|
+
<section data-instrument aria-label={label}>
|
|
710
|
+
<style>{FACE}</style>
|
|
711
|
+
<Screws />
|
|
712
|
+
<span className="ix-plate">{plate}</span>
|
|
713
|
+
{children}
|
|
714
|
+
</section>
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// Sixteen step lights; the lit one follows the playhead.
|
|
719
|
+
function Lights({ step }) {
|
|
720
|
+
return (
|
|
721
|
+
<div className="ix-lights" aria-hidden="true">
|
|
722
|
+
{Array.from({ length: STEPS }, (_, i) => (
|
|
723
|
+
<span key={i} className="ix-light" data-on={i === step || undefined} />
|
|
724
|
+
))}
|
|
725
|
+
</div>
|
|
726
|
+
);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// Play, Clear and the tempo readout.
|
|
730
|
+
function Transport({ m }) {
|
|
731
|
+
return (
|
|
732
|
+
<Row gap={3} align="center" wrap>
|
|
733
|
+
<Button onClick={m.togglePlay}>{m.playing ? "Stop" : "Play"}</Button>
|
|
734
|
+
<Button size="sm" variant="quiet" onClick={m.clear}>
|
|
735
|
+
Clear
|
|
736
|
+
</Button>
|
|
737
|
+
<Spacer />
|
|
738
|
+
<span className="ix-lcd">{String(m.bpm).padStart(3, "0")} BPM</span>
|
|
739
|
+
</Row>
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// Tempo, Swing, Drive and Volume: four 56px knobs fit a phone's width in one row.
|
|
744
|
+
function Knobs({ m }) {
|
|
745
|
+
return (
|
|
746
|
+
<Row gap={2} align="center" justify="between">
|
|
747
|
+
<Knob label="Tempo" value={m.bpm} min={60} max={180} shown={m.bpm} onChange={m.setBpm} />
|
|
748
|
+
<Knob label="Swing" value={m.swing} min={0} max={100} shown={`${m.swing}%`} onChange={m.setSwing} />
|
|
749
|
+
<Knob label="Drive" value={m.drive} min={0} max={100} shown={`${m.drive}%`} onChange={m.setDrive} />
|
|
750
|
+
<Knob label="Volume" value={m.volume} min={0} max={100} shown={`${m.volume}%`} onChange={m.setVolume} />
|
|
751
|
+
</Row>
|
|
752
|
+
);
|
|
753
|
+
}
|
|
754
|
+
// Three arrangements. Choose one, name it in the picks line, and render it inside App after
|
|
755
|
+
// `const m = useDrumMachine();`. Saving, sharing and the list of saved beats are the app's own,
|
|
756
|
+
// built from the Fireproof and access docs as ordinary Cards outside the panel.
|
|
757
|
+
|
|
758
|
+
// Rows: every voice is a line of steps, the classic drum machine.
|
|
759
|
+
function RowsPanel({ m }) {
|
|
760
|
+
return (
|
|
761
|
+
<Panel label="Drum machine" plate="Jam box · 16-step">
|
|
762
|
+
<Transport m={m} />
|
|
763
|
+
<Knobs m={m} />
|
|
764
|
+
<Lights step={m.step} />
|
|
765
|
+
<div className="ix-well">
|
|
766
|
+
{TRACKS.map(({ id, label }) => (
|
|
767
|
+
<Stack key={id} gap={1}>
|
|
768
|
+
<span className="ix-label">{label}</span>
|
|
769
|
+
<StepGrid label={label} steps={m.grid[id]} playhead={m.step} onToggle={(i) => m.toggleStep(id, i)} />
|
|
770
|
+
</Stack>
|
|
771
|
+
))}
|
|
772
|
+
</div>
|
|
773
|
+
</Panel>
|
|
774
|
+
);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
// Pad grid: big voice pads choose a sound (and play it); its sixteen steps sit four by four.
|
|
778
|
+
function PadGridPanel({ m }) {
|
|
779
|
+
const [voice, setVoice] = useState(TRACKS[0].id);
|
|
780
|
+
return (
|
|
781
|
+
<Panel label="Drum pads" plate="Pad 16">
|
|
782
|
+
<div className="ix-voices">
|
|
783
|
+
{TRACKS.map(({ id, label }) => (
|
|
784
|
+
<Button key={id} variant={voice === id ? undefined : "quiet"} onClick={() => { m.hit(id); setVoice(id); }}>
|
|
785
|
+
{label}
|
|
786
|
+
</Button>
|
|
787
|
+
))}
|
|
788
|
+
</div>
|
|
789
|
+
<div className="ix-well ix-grid4">
|
|
790
|
+
<StepGrid label={voice} steps={m.grid[voice]} playhead={m.step} onToggle={(i) => m.toggleStep(voice, i)} />
|
|
791
|
+
</div>
|
|
792
|
+
<Transport m={m} />
|
|
793
|
+
<Knobs m={m} />
|
|
794
|
+
</Panel>
|
|
795
|
+
);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// Vertical rack: each voice is its own rack unit, stacked, with its name plate and a hit button.
|
|
799
|
+
function RackPanel({ m }) {
|
|
800
|
+
return (
|
|
801
|
+
<Panel label="Drum rack" plate="Rack · 4 voices">
|
|
802
|
+
<Transport m={m} />
|
|
803
|
+
{TRACKS.map(({ id, label }) => (
|
|
804
|
+
<div key={id} className="ix-unit">
|
|
805
|
+
<Screws />
|
|
806
|
+
<Row gap={2} align="center">
|
|
807
|
+
<span className="ix-plate">{label}</span>
|
|
808
|
+
<Spacer />
|
|
809
|
+
<Button size="sm" variant="quiet" onClick={() => m.hit(id)}>
|
|
810
|
+
Hit
|
|
811
|
+
</Button>
|
|
812
|
+
</Row>
|
|
813
|
+
<StepGrid label={label} steps={m.grid[id]} playhead={m.step} onToggle={(i) => m.toggleStep(id, i)} />
|
|
814
|
+
</div>
|
|
815
|
+
))}
|
|
816
|
+
<Knobs m={m} />
|
|
817
|
+
</Panel>
|
|
818
|
+
);
|
|
819
|
+
}
|
|
820
|
+
```
|
|
821
|
+
|
|
822
|
+
### The instrument face — hardware painted from the look
|
|
823
|
+
|
|
824
|
+
Every drum machine wears an instrument face from its first build: one
|
|
825
|
+
`<section data-instrument>` panel that holds the pads, the transport and the
|
|
826
|
+
knobs, so it reads as a machine you could pick up. The face is the app's own
|
|
827
|
+
instrument, so a look brief, a layout archetype or a reskin dose on the same
|
|
828
|
+
turn dresses the page around it, and the face keeps its knobs, pads and
|
|
829
|
+
token-painted panel. The heading, the save row and the saved list stay ordinary
|
|
830
|
+
`Card`s outside the panel, so the rest of the app keeps the look's own
|
|
831
|
+
components. When the person names a machine or a material ("an 808", "a
|
|
832
|
+
vintage beat box", "an MPC", "brushed metal"), this face is how it gets there.
|
|
833
|
+
|
|
834
|
+
**Paint from the look's tokens.** Every colour in the face is a `color-mix` of
|
|
835
|
+
the look's tokens: `--bg --surface --ink --purple --orange --info --up
|
|
836
|
+
--on-accent`, with `--r-card --r-control` for corners and `--font-family` for
|
|
837
|
+
type. The face assigns no value to a token and writes no hex colour, so the
|
|
838
|
+
Look tab's colours and every look in the look picker, light and dark,
|
|
839
|
+
repaint the whole machine, and each look gives the same
|
|
840
|
+
drum machine a different body. **Every fill starts from `--surface`.** The panel,
|
|
841
|
+
the well, the readout window, the knob caps and the unlit pads are `--surface`
|
|
842
|
+
with a small share of `--ink` (75% `--surface` or more), so they stay a body
|
|
843
|
+
the look's own colour on light looks and on dark ones like Terminal, where
|
|
844
|
+
`--ink` is the light colour. Text, borders, bezels and shadows are where `--ink`
|
|
845
|
+
leads. The readout is a recessed `--surface` window with `--ink` glyphs tinted
|
|
846
|
+
by the LED colour, readable in both polarities; the LEDs are the LED role on
|
|
847
|
+
that body. Focus outlines are `--ink`, since an LED colour can sit close to the
|
|
848
|
+
panel.
|
|
849
|
+
|
|
850
|
+
**The pads stay `StepGrid`.** Style them from the panel through their hooks:
|
|
851
|
+
`.ui-pad[data-state="on"]` and `[data-state="off"]` (give both a fill, because
|
|
852
|
+
a look's button rule paints a pad otherwise), `[data-group]` (0 to 3 across a
|
|
853
|
+
bar), `[data-playhead]`, `.ui-pad__led` and `.ui-pad__ring`.
|
|
854
|
+
|
|
855
|
+
**Make it yours: every first build chooses one per axis** and names the picks
|
|
856
|
+
as the first line of `FACE`, in the reference's shape:
|
|
857
|
+
`/* picks: arrangement = … · pad = … · panel = … · led = … · transport = … */`.
|
|
858
|
+
Choose from what the person asked for and what the app is about; when the
|
|
859
|
+
turn carries an "Instrument arrangement" section, that is this app's
|
|
860
|
+
arrangement. The
|
|
861
|
+
reference's picks are one combination; keep one only when it is the right one
|
|
862
|
+
for this app, so two drum machines rarely share all five. Each pick is a few
|
|
863
|
+
lines of the sheet or the markup.
|
|
864
|
+
|
|
865
|
+
- **Arrangement:** tracks as rows (one `StepGrid` per voice, stacked, as in the
|
|
866
|
+
reference); a pad grid (four big voice pads choose which voice to edit, and a
|
|
867
|
+
single `StepGrid` for that voice is laid out four by four with
|
|
868
|
+
`--ui-steps: 4; --ui-steps-narrow: 4` on `.ui-stepgrid`, MPC style); or a
|
|
869
|
+
vertical rack (each voice its own rack unit, stacked: a name plate, a mute
|
|
870
|
+
or level knob and its step row, with a rail and screws per unit).
|
|
871
|
+
|
|
872
|
+
- **Pad shape:** square key (small radius, hard bottom edge), rubber pad
|
|
873
|
+
(`border-radius: 30%`, inset shadow), or round cap (`50%`).
|
|
874
|
+
- **Panel material:** flat plate, brushed metal (a `repeating-linear-gradient`
|
|
875
|
+
of two `--surface`-led mixes), or wood cheeks (thick side borders mixed from `--orange`
|
|
876
|
+
and `--ink`).
|
|
877
|
+
- **LED colour role:** `--info`, `--orange` or `--up`, which lights the
|
|
878
|
+
playhead ring, the step lights and the readout.
|
|
879
|
+
- **Transport layout:** a strip above the grid, a deck below it, or a column
|
|
880
|
+
beside it on wide screens.
|
|
881
|
+
- **Beat-group colours:** four accents across the bar, two-tone by parity, or
|
|
882
|
+
one tone with the lights doing the work.
|
|
883
|
+
|
|
884
|
+
**Hardware cues, all from tokens:** a bezel (`2px solid var(--ink)`,
|
|
885
|
+
`var(--r-card)`), four screws, a printed name plate, a row of step lights over
|
|
886
|
+
the grid, a readout for the tempo, and knobs. A knob is a plain `div` with
|
|
887
|
+
`role="slider"`: drag up to turn it, arrow keys step it, at least 56px across.
|
|
888
|
+
On a phone the grid runs eight pads a line, so every pad, button and knob stays
|
|
889
|
+
thumb-sized.
|
|
890
|
+
|
|
891
|
+
The parts above carry this face (`FACE`, `Knob`, `Screws`, `Lights`,
|
|
892
|
+
`Transport`, `Knobs`), and each sketch is one arrangement of them. A first build
|
|
893
|
+
picks an arrangement and the other axes; keep every colour a token mix.
|
|
894
|
+
|
|
895
|
+
— End —
|