Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

Beatbox mode: a physically modelled beatboxer with a sample-accurate sequencer

Jameson Hodge64daac4618a6
diff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.ts
index bcdd92b..75c9e5a 100644
--- a/src/audio/AudioEngine.ts
+++ b/src/audio/AudioEngine.ts
@@ -18,6 +18,9 @@ export class AudioEngine {
/** long time-domain window for the waveform scope */
analyserScope: AnalyserNode | null = null;
private master: GainNode | null = null;
+ /** "close mic" chain: proximity bass, presence, compression (beatboxers cup the mic) */
+ private micIn: AudioNode | null = null;
+ private micOn = false;
latest: TelemetryMessage | null = null;
latestCreature: CreatureTelemetryMessage | null = null;
/** load of the most recent telemetry of either kind */
@@ -65,7 +68,27 @@ export class AudioEngine {
const scope = ctx.createAnalyser();
scope.fftSize = 16384;
this.analyserScope = scope;
- node.connect(master);
+ // close-mic chain: proximity effect (low shelf), presence peak, fast compressor, make-up
+ const shelf = ctx.createBiquadFilter();
+ shelf.type = "lowshelf";
+ shelf.frequency.value = 120;
+ shelf.gain.value = 9;
+ const presence = ctx.createBiquadFilter();
+ presence.type = "peaking";
+ presence.frequency.value = 3500;
+ presence.Q.value = 0.8;
+ presence.gain.value = 3;
+ const comp = ctx.createDynamicsCompressor();
+ comp.threshold.value = -28;
+ comp.knee.value = 8;
+ comp.ratio.value = 5;
+ comp.attack.value = 0.002;
+ comp.release.value = 0.12;
+ const makeup = ctx.createGain();
+ makeup.gain.value = 2.2;
+ shelf.connect(presence).connect(comp).connect(makeup).connect(master);
+ this.micIn = shelf;
+ node.connect(this.micOn ? shelf : master);
master.connect(ctx.destination);
master.connect(analyser);
master.connect(fast);
@@ -144,6 +167,23 @@ export class AudioEngine {
this.node?.port.postMessage(m);
}
+ /** Route the voice through the close-mic chain (on) or straight to the output (off). */
+ setMic(on: boolean): void {
+ if (on === this.micOn) return;
+ this.micOn = on;
+ if (!this.node || !this.master || !this.micIn) return;
+ this.node.disconnect();
+ this.node.connect(on ? this.micIn : this.master);
+ }
+
+ setBeat(m: { steps?: import("../engine/phonetics/beatbox.ts").BeatStep[] | (import("../engine/phonetics/beatbox.ts").BeatStep | null)[]; bpm?: number; swing?: number; playing?: boolean }): void {
+ this.send({ type: "beat", ...m });
+ }
+
+ beatHit(id: string, note?: number, accent?: number): void {
+ this.send({ type: "beatHit", id, note, accent });
+ }
+
setVolume(v: number): void {
if (this.master && this.ctx) this.master.gain.setTargetAtTime(v, this.ctx.currentTime, 0.02);
}
diff --git a/src/engine/control/beatPlayer.ts b/src/engine/control/beatPlayer.ts
new file mode 100644
index 0000000..d26257f
--- /dev/null
+++ b/src/engine/control/beatPlayer.ts
@@ -0,0 +1,108 @@
+/**
+ * Step sequencer for the beatboxer. Runs on the voice clock (in the AudioWorklet, or offline),
+ * so hits are sample-accurate whatever the main thread is doing. Each step's gestures are built
+ * when its hit comes within `horizon` of the clock: early enough for the slowest sound's set-up,
+ * late enough that edits to the pattern are heard within a step or two.
+ */
+import { beatSound, BASS_NOTE, type BeatStep } from "../phonetics/beatbox.ts";
+import type { Gesture } from "./score.ts";
+
+const midiToHz = (m: number) => 440 * Math.pow(2, (m - 69) / 12);
+
+export class BeatPlayer {
+ steps: (BeatStep | null)[] = [];
+ bpm = 96;
+ /** 0..0.6: off-beat sixteenths are delayed by swing × half a step */
+ swing = 0;
+ readonly stepsPerBeat = 4;
+ playing = false;
+ body = "male";
+ /** schedule a step when its hit is this close (s); covers every sound's set-up time */
+ readonly horizon = 0.2;
+ private anchorTime = 0;
+ private anchorStep = 0;
+ private next = 0;
+
+ get stepDur(): number {
+ return 60 / this.bpm / this.stepsPerBeat;
+ }
+
+ private stepTime(n: number): number {
+ const base = this.anchorTime + (n - this.anchorStep) * this.stepDur;
+ return n % 2 === 1 ? base + this.swing * 0.5 * this.stepDur : base;
+ }
+
+ start(clock: number): void {
+ this.playing = true;
+ this.anchorTime = clock + this.horizon;
+ this.anchorStep = 0;
+ this.next = 0;
+ }
+
+ stop(): void {
+ this.playing = false;
+ }
+
+ /** Change tempo without a jump: the next unscheduled step keeps its time. */
+ setTempo(bpm: number, swing: number): void {
+ const b = Math.min(200, Math.max(40, bpm));
+ if (this.playing && b !== this.bpm) {
+ this.anchorTime += (this.next - this.anchorStep) * this.stepDur;
+ this.anchorStep = this.next;
+ }
+ this.bpm = b;
+ this.swing = Math.min(0.6, Math.max(0, swing));
+ }
+
+ /** The voice clock restarted (new voice after a body change): keep the beat's phase. */
+ rebase(delta: number): void {
+ this.anchorTime += delta;
+ }
+
+ /** Step under the playhead at `clock` (−1 when stopped). */
+ stepAt(clock: number): number {
+ if (!this.playing || this.steps.length === 0) return -1;
+ const n = Math.floor((clock - this.anchorTime) / this.stepDur) + this.anchorStep;
+ return n < 0 ? -1 : n % this.steps.length;
+ }
+
+ /** Schedule every step whose hit falls within the horizon. */
+ tick(clock: number, schedule: (gs: Gesture[]) => void): void {
+ if (!this.playing || this.steps.length === 0) return;
+ for (let guard = 0; guard < 64; guard++) {
+ const hit = this.stepTime(this.next);
+ if (hit > clock + this.horizon) break;
+ const L = this.steps.length;
+ const cell = this.steps[this.next % L];
+ if (cell && hit >= clock) {
+ // sustained sounds (hum, open hat) last until the next sound
+ let rests = 0;
+ while (rests < L - 1 && !this.steps[(this.next + 1 + rests) % L]) rests++;
+ schedule(this.gestures(cell, hit, (1 + rests) * this.stepDur));
+ }
+ this.next++;
+ }
+ }
+
+ /** Gestures for one sound whose acoustic hit lands at `hit` on the voice clock. */
+ gestures(cell: BeatStep, hit: number, len = this.stepDur): Gesture[] {
+ const s = beatSound(cell.id);
+ if (!s) return [];
+ const gs = s.build(this.body, { f0: midiToHz(cell.note ?? BASS_NOTE), len, accent: cell.accent ?? 1 });
+ const off = hit - s.latency;
+ for (const g of gs) {
+ g.t0 += off;
+ g.t1 += off;
+ }
+ return gs;
+ }
+
+ /** Set-up time a sound needs before its hit (s): when a pad press can sound at the earliest. */
+ static leadIn(id: string, body = "male"): number {
+ const s = beatSound(id);
+ if (!s) return 0;
+ let lead = 0;
+ for (const g of s.build(body, { f0: 100, len: 0.15, accent: 1 })) lead = Math.max(lead, -(g.t0 - g.rampIn));
+ return lead + s.latency;
+ }
+}
diff --git a/src/engine/phonetics/beatbox.ts b/src/engine/phonetics/beatbox.ts
new file mode 100644
index 0000000..4d6fb2f
--- /dev/null
+++ b/src/engine/phonetics/beatbox.ts
@@ -0,0 +1,282 @@
+/**
+ * A physically modelled beatboxer. Each drum sound is a short gestural score on the human vocal
+ * tract, made with the airstream mechanisms beatboxers actually use:
+ * - pulmonic: breath from the lungs (snares, hats, crash)
+ * - glottalic (ejective): the glottis sealed, the larynx rises like a piston and compresses the
+ * air behind an oral closure (kick, rimshot): punchy, dry, no breath noise
+ * - velaric (click): the tongue seals a pocket against the palate and hollows it; the release
+ * pops inward (tongue click, lip pop)
+ * - ingressive: breath drawn in through a constriction (inward K snare)
+ * - voiced: a hummed bass through the nose
+ * One throat makes one sound at a time, so patterns are monophonic like a real beatboxer's.
+ * Symbols follow Standard Beatbox Notation where it has one.
+ */
+import type { Gesture } from "../control/score.ts";
+import type { HumanArtic } from "../anatomy/human.ts";
+import { phoneme } from "./inventory.ts";
+import { oralGestures, vowelArtic } from "./planner.ts";
+
+/** A beatboxer's ready posture: jaw nearly closed, lips just apart, tongue relaxed. */
+export function beatReady(body: string): Partial<HumanArtic> {
+ return { ...(vowelArtic("ə", body) ?? {}), jaw: 0.4, lipAp: 0.25, lipProt: 0.1 };
+}
+
+export type BeatRole = "kick" | "snare" | "hat" | "perc" | "bass";
+export type Airstream = "pulmonic" | "ejective" | "click" | "ingressive" | "voiced";
+
+export interface BeatBuild {
+ /** hum pitch (Hz) */
+ f0: number;
+ /** how long the sound may last (s): its step length, for sustained sounds */
+ len: number;
+ /** loudness 0.5..1.5 */
+ accent: number;
+}
+
+export interface BeatSound {
+ /** pattern symbol */
+ id: string;
+ name: string;
+ role: BeatRole;
+ airstream: Airstream;
+ hint: string;
+ /**
+ * Gestures with the acoustic hit at t = 0. `latency` (s) is the measured delay from the
+ * planned hit to the acoustic onset; the sequencer schedules that much earlier.
+ */
+ build(body: string, o: BeatBuild): Gesture[];
+ latency: number;
+}
+
+const oral = (body: string, ipa: string, a: number, b: number, speed: number, label: string, extra: Record<string, number> = {}): Gesture[] => {
+ const d = phoneme(ipa, body);
+ if (!d) return [];
+ return oralGestures(d, { ...d.targets, ...extra }, a, b, speed, label);
+};
+
+const g = (t0: number, t1: number, rampIn: number, rampOut: number, strength: number, targets: Gesture["targets"], label: string, speed?: number): Gesture => ({ t0, t1, rampIn, rampOut, strength, targets, label, speed });
+
+/** Beatboxers snap their releases: faster than speech, and the heavy dorsum is no exception. */
+const snap = (gs: Gesture[], speed = 3.5, rampOut = 0.01): Gesture[] => {
+ for (const x of gs) if (x.strength >= 40) {
+ x.speed = speed;
+ x.rampOut = rampOut;
+ }
+ return gs;
+};
+
+/**
+ * A release fricative that starts only after the burst: with the planner's 30 ms ramp it would
+ * grip the articulators while the closure is still held and pry it open early.
+ */
+const after = (gs: Gesture[], rampIn = 0.008): Gesture[] => {
+ for (const x of gs) x.rampIn = Math.min(x.rampIn, rampIn);
+ return gs;
+};
+
+/** Glottalic piston: glottis sealed through the closure, larynx raised just before release. */
+const ejective = (a: number, accent: number, label: string): Gesture[] => [
+ g(a - 0.012, 0.03, 0.012, 0.03, 8, { closure: 1 }, label),
+ g(-0.05, 0.004, 0.03, 0.08, 40, { larynx: Math.min(1.6, 1.25 + 0.3 * accent) }, label, 3),
+];
+
+/**
+ * Lung pressure (× the performer's breath pressure) over [a, b], with the glottis held open
+ * until the breath has gone (otherwise the folds start to vibrate on the leftover pressure).
+ */
+const blow = (a: number, b: number, level: number, abduction: number, label: string, tail = 0.03): Gesture[] => [
+ g(a, b + tail + 0.02, 0.02, 0.03, 6, { abduction }, label),
+ g(a - 0.01, b, 0.02, tail, 1, { breath: level }, label),
+];
+
+export const BEAT_SOUNDS: BeatSound[] = [
+ {
+ id: "B",
+ name: "Kick",
+ role: "kick",
+ airstream: "ejective",
+ hint: "Lips burst on air the rising larynx compresses",
+ latency: 0.01,
+ build: (body, o) => [...snap(oral(body, "p", -0.075, 0, 2, "B", { jaw: 0.3 })), ...ejective(-0.075, o.accent, "B")],
+ },
+ {
+ id: "t",
+ name: "Hi-hat",
+ role: "hat",
+ airstream: "pulmonic",
+ hint: "Tongue-tip release into a short hiss",
+ latency: -0.005,
+ build: (body, o) => [...snap(oral(body, "t", -0.05, 0, 2, "t", { jaw: 0.3 })), ...after(oral(body, "s", 0.012, 0.03, 1.6, "t")), ...blow(-0.03, 0.026, 1.25 * o.accent, 0.36, "t", 0.02)],
+ },
+ {
+ id: "tss",
+ name: "Open hat",
+ role: "hat",
+ airstream: "pulmonic",
+ hint: "The hi-hat left ringing as a long hiss",
+ latency: -0.005,
+ build: (body, o) => {
+ const end = Math.max(0.09, Math.min(0.26, o.len * 1.6));
+ return [...snap(oral(body, "t", -0.05, 0, 2, "tss", { jaw: 0.3 })), ...after(oral(body, "s", 0.012, end, 1.4, "tss")), ...blow(-0.03, end, 1.2 * o.accent, 0.4, "tss", 0.09)];
+ },
+ },
+ {
+ id: "Pf",
+ name: "Snare",
+ role: "snare",
+ airstream: "pulmonic",
+ hint: "Lips burst, then the lower lip hisses against the teeth",
+ latency: 0.018,
+ build: (body, o) => [...snap(oral(body, "p", -0.06, 0, 2, "Pf")), ...after(oral(body, "f", 0.018, 0.08, 1.6, "Pf")), ...blow(-0.045, 0.075, 1.7 * o.accent, 0.45, "Pf", 0.04)],
+ },
+ {
+ id: "K",
+ name: "Rimshot",
+ role: "snare",
+ airstream: "ejective",
+ hint: "Back of the tongue bursts on larynx-compressed air",
+ latency: 0.009,
+ build: (body, o) => [...snap(oral(body, "k", -0.08, 0, 2, "K", { jaw: 0.35 }), 4, 0.008), ...ejective(-0.08, o.accent, "K")],
+ },
+ {
+ id: "^K",
+ name: "Inward snare",
+ role: "snare",
+ airstream: "ingressive",
+ hint: "A sharp breath in past the back of the tongue",
+ latency: -0.002,
+ build: (body, o) => [
+ ...snap(oral(body, "k", -0.06, 0, 2, "^K", { jaw: 0.35 }), 4, 0.008),
+ ...after(oral(body, "x", 0.012, 0.085, 1.4, "^K", { tbY: 7.35 })),
+ g(-0.05, 0.085, 0.02, 0.04, 6, { abduction: 0.5 }, "^K"),
+ // draw the breath in behind the closure so the release rushes inward
+ g(-0.035, 0.085, 0.015, 0.05, 2, { breath: -1.7 * o.accent }, "^K"),
+ ],
+ },
+ {
+ id: "!",
+ name: "Tongue click",
+ role: "perc",
+ airstream: "click",
+ hint: "Tongue seals a pocket, hollows it and pops",
+ latency: -0.007,
+ build: (body) => [
+ ...snap(oral(body, "t", -0.12, 0, 2, "!")),
+ ...oral(body, "k", -0.12, 0.035, 2, "!"),
+ g(-0.03, 0.006, 0.04, 0.03, 40, { dorsum: 1 }, "!", 2),
+ ],
+ },
+ {
+ id: "P!",
+ name: "Lip pop",
+ role: "perc",
+ airstream: "click",
+ hint: "Sealed lips, the jaw drops, the lips pop open",
+ latency: 0.013,
+ build: (body) => [
+ ...snap(oral(body, "p", -0.12, 0, 2, "P!")),
+ ...oral(body, "k", -0.12, 0.03, 2, "P!"),
+ // lips stay sealed while the jaw and tongue hollow the mouth
+ g(-0.045, 0.004, 0.04, 0.05, 40, { jaw: 1.3, dorsum: 0.8 }, "P!", 1.6),
+ ],
+ },
+ {
+ id: "kch",
+ name: "Crash",
+ role: "hat",
+ airstream: "pulmonic",
+ hint: "Back-of-tongue release into a long rounded hiss",
+ latency: -0.001,
+ build: (body, o) => {
+ const end = Math.max(0.14, Math.min(0.34, o.len * 2));
+ return [...snap(oral(body, "k", -0.06, 0, 2, "kch"), 4, 0.008), ...after(oral(body, "ʃ", 0.014, end, 1.4, "kch")), ...blow(-0.035, end, 1.45 * o.accent, 0.45, "kch", 0.14)];
+ },
+ },
+ {
+ id: "m",
+ name: "Hum",
+ role: "bass",
+ airstream: "voiced",
+ hint: "Hummed bass note through the nose",
+ latency: 0.012,
+ build: (body, o) => {
+ const end = Math.max(0.06, o.len * 0.92);
+ return [
+ // lips shut before the voice starts, so the note begins as a hum rather than a vowel
+ ...oral(body, "m", -0.03, end, 1.6, "m"),
+ g(-0.02, end, 0.03, 0.03, 4, { velum: 0.9 }, "m"),
+ g(-0.01, end, 0.02, 0.04, 1, { breath: 0.95 * o.accent }, "m"),
+ g(-0.02, end, 0.015, 0.02, 8, { f0: o.f0 }, "m"),
+ ];
+ },
+ },
+];
+
+const BY_ID = new Map(BEAT_SOUNDS.map((s) => [s.id, s]));
+export const beatSound = (id: string): BeatSound | undefined => BY_ID.get(id);
+
+/** One step of a pattern: a sound (null = rest), optional MIDI note for pitched sounds. */
+export interface BeatStep {
+ id: string;
+ note?: number;
+ accent?: number;
+}
+
+/** Default hum note (MIDI E2) */
+export const BASS_NOTE = 40;
+
+/**
+ * Parse a beat written as text: tokens separated by spaces or "|" (bar lines, ignored);
+ * "." or "-" is a rest; a hum may carry a MIDI note ("m:43"); a trailing ">" accents.
+ */
+export function parseBeat(text: string): (BeatStep | null)[] {
+ const out: (BeatStep | null)[] = [];
+ for (const raw of text.split(/[\s|]+/)) {
+ if (!raw) continue;
+ if (raw === "." || raw === "-") {
+ out.push(null);
+ continue;
+ }
+ let tok = raw;
+ let accent: number | undefined;
+ if (tok.endsWith(">")) {
+ accent = 1.3;
+ tok = tok.slice(0, -1);
+ }
+ let note: number | undefined;
+ const m = /^(.+?):(\d+)$/.exec(tok);
+ if (m) {
+ tok = m[1];
+ note = Number(m[2]);
+ }
+ const s = BY_ID.get(tok) ?? BEAT_SOUNDS.find((x) => x.id.toLowerCase() === tok.toLowerCase());
+ if (s) out.push({ id: s.id, ...(note !== undefined ? { note } : {}), ...(accent ? { accent } : {}) });
+ else out.push(null);
+ }
+ return out;
+}
+
+/** Inverse of parseBeat: four steps per group, groups separated by spaces. */
+export function formatBeat(steps: (BeatStep | null)[]): string {
+ const toks = steps.map((s) => (s ? `${s.id}${s.note !== undefined ? `:${s.note}` : ""}${s.accent && s.accent > 1 ? ">" : ""}` : "."));
+ const groups: string[] = [];
+ for (let i = 0; i < toks.length; i += 4) groups.push(toks.slice(i, i + 4).join(" "));
+ return groups.join(" | ");
+}
+
+export interface BeatPreset {
+ name: string;
+ bpm: number;
+ swing: number;
+ text: string;
+}
+
+export const BEAT_PRESETS: BeatPreset[] = [
+ { name: "Boots and cats", bpm: 96, swing: 0, text: "B . t . | Pf . t . | B . t . | Pf . t ." },
+ { name: "Four on the floor", bpm: 122, swing: 0, text: "B . t . | B . tss . | B . t . | B . tss ." },
+ { name: "Breakbeat", bpm: 94, swing: 0.18, text: "B . t . | Pf . t B | . B t . | Pf . t t" },
+ { name: "Rimshot shuffle", bpm: 88, swing: 0.4, text: "B . t K | . t B . | t . K t | . B K t" },
+ { name: "Inward snare", bpm: 100, swing: 0, text: "B . t . | ^K . t . | B B t . | ^K . t ." },
+ { name: "Clicks and pops", bpm: 90, swing: 0.25, text: "B . ! . | P! . ! . | B ! . ! | P! . ! !" },
+ { name: "Hum bass", bpm: 92, swing: 0.1, text: "B m . m:43 | Pf . m:45 . | B m:40 . m | Pf . t kch" },
+];
diff --git a/src/engine/phonetics/planner.ts b/src/engine/phonetics/planner.ts
index 6de8b3b..d7f06f0 100644
--- a/src/engine/phonetics/planner.ts
+++ b/src/engine/phonetics/planner.ts
@@ -125,26 +125,7 @@ export function planUtterance(input: Segment[], o: PlanOptions): Plan {
const prevVowel = i > 0 && !!segs[i - 1].vowel;
const nextVowel = i < segs.length - 1 && !!segs[i + 1].vowel;
const prevSeg = i > 0 ? segs[i - 1] : null;
- const addOral = (tg: Partial<HumanArtic>, a: number, b: number, speed: number, label: string) => {
- const dom: Partial<HumanArtic> = {};
- const sec: Partial<HumanArtic> = {};
- for (const [k, v] of Object.entries(tg) as [keyof HumanArtic, number][]) (def.dominant.includes(k) ? dom : sec)[k] = v;
- // the dorsum is heavy: its releases are slower than tip and lip releases
- const bodyOnly = def.dominant.every((k) => k === "tbX" || k === "tbY" || k === "root");
- const sp = bodyOnly ? 1 + (speed - 1) * 0.35 : speed;
- // articulators need ~10–15 ms to climb out of the overshoot (contact) target, so the
- // gesture releases early and the acoustic release lands on the planned boundary
- // measured movement latencies (closure lag / release lag) per articulator class, so the
- // acoustic closure and release land on the planned segment boundaries
- const closing = def.manner === "stop" || def.manner === "nasal" || def.manner === "affricate";
- const lipsOnly = def.dominant.every((k) => k === "lipAp" || k === "labiodental");
- const lead = closing ? (bodyOnly ? 0.034 : lipsOnly ? 0.019 : 0.02) : 0;
- // a consonant must own its constriction articulators (Task-Dynamics style): at strength 40
- // the overlapping vowel contributes ~2 %, so closures seal instead of being diluted
- const early = closing ? (bodyOnly ? 0.024 : lipsOnly ? 0.022 : 0.031) : 0.008;
- if (Object.keys(dom).length) gestures.push({ t0: a - early, t1: Math.max(a + 0.01, b - lead), rampIn: 0.03, rampOut: bodyOnly ? 0.03 : 0.018, strength: 40, targets: dom, speed: sp, releaseHold: 0.045, label });
- if (Object.keys(sec).length) gestures.push({ t0: a, t1: b, rampIn: 0.05, rampOut: 0.05, strength: 2.2, targets: sec, label });
- };
+ const addOral = (tg: Partial<HumanArtic>, a: number, b: number, speed: number, label: string) => gestures.push(...oralGestures(def, tg, a, b, speed, label));
switch (def.manner) {
case "stop":
case "nasal":
@@ -223,6 +204,33 @@ export function planUtterance(input: Segment[], o: PlanOptions): Plan {
return { gestures, segments: planned, end };
}
+/**
+ * Oral gestures for one consonant constriction held acoustically from `a` to `b` (closure to
+ * release): a dominant gesture on the consonant's own articulators and a weak one on the rest.
+ * Movement latencies are compensated so the acoustic closure and release land on a and b.
+ */
+export function oralGestures(def: PhonemeDef, tg: Partial<HumanArtic>, a: number, b: number, speed: number, label: string): Gesture[] {
+ const out: Gesture[] = [];
+ const dom: Partial<HumanArtic> = {};
+ const sec: Partial<HumanArtic> = {};
+ for (const [k, v] of Object.entries(tg) as [keyof HumanArtic, number][]) (def.dominant.includes(k) ? dom : sec)[k] = v;
+ // the dorsum is heavy: its releases are slower than tip and lip releases
+ const bodyOnly = def.dominant.every((k) => k === "tbX" || k === "tbY" || k === "root");
+ const sp = bodyOnly ? 1 + (speed - 1) * 0.35 : speed;
+ // articulators need ~10–15 ms to climb out of the overshoot (contact) target, so the
+ // gesture releases early and the acoustic release lands on the planned boundary:
+ // measured movement latencies (closure lag / release lag) per articulator class
+ const closing = def.manner === "stop" || def.manner === "nasal" || def.manner === "affricate";
+ const lipsOnly = def.dominant.every((k) => k === "lipAp" || k === "labiodental");
+ const lead = closing ? (bodyOnly ? 0.034 : lipsOnly ? 0.019 : 0.02) : 0;
+ // a consonant must own its constriction articulators (Task-Dynamics style): at strength 40
+ // the overlapping vowel contributes ~2 %, so closures seal instead of being diluted
+ const early = closing ? (bodyOnly ? 0.024 : lipsOnly ? 0.022 : 0.031) : 0.008;
+ if (Object.keys(dom).length) out.push({ t0: a - early, t1: Math.max(a + 0.01, b - lead), rampIn: 0.03, rampOut: bodyOnly ? 0.03 : 0.018, strength: 40, targets: dom, speed: sp, releaseHold: 0.045, label });
+ if (Object.keys(sec).length) out.push({ t0: a, t1: b, rampIn: 0.05, rampOut: 0.05, strength: 2.2, targets: sec, label });
+ return out;
+}
+
/** Plan consecutive phrases (each with its own breath group and intonation) from t0. */
export function planPhrases(
phrases: { segments: Segment[]; intonation?: "statement" | "question" | "flat"; pause?: number }[],
diff --git a/src/engine/voice/humanVoice.ts b/src/engine/voice/humanVoice.ts
index ac47be1..41f7a68 100644
--- a/src/engine/voice/humanVoice.ts
+++ b/src/engine/voice/humanVoice.ts
@@ -291,7 +291,9 @@ export class HumanVoice {
// a negative breath gesture (ingressive: inward K snares, gasps) overrides the performer's breath
const scoreBreath = breathVal * breathAct;
const gateGoal = scoreBreath < 0 ? scoreBreath : Math.max(this.gateTarget, scoreBreath);
- const tau = gateGoal > this.gate ? 0.025 : 0.07;
+ // a score shapes its own breath ramps (beatbox hits end their breath abruptly); the slow
+ // release is for the performer's note-offs
+ const tau = gateGoal > this.gate ? 0.025 : breathAct > 0 ? 0.02 : 0.07;
this.gate += (gateGoal - this.gate) * (1 - Math.exp(-dt / tau));
this.pLung = this.source.pressure * CM_H2O * this.gate;
// pitch glide
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index c015849..865e26c 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -17,6 +17,7 @@ import { Spectrogram } from "./components/Spectrogram.tsx";
import { Scope } from "./components/Scope.tsx";
import { CreatureTubes } from "./components/CreatureTubes.tsx";
import { creatureById } from "../engine/creatures/index.ts";
+import { BeatboxPanel, BeatOverlay } from "./components/BeatboxPanel.tsx";
import type { Mode } from "./store.ts";
import type { BodyName } from "../worklet/protocol.ts";
@@ -49,6 +50,7 @@ function TopBar() {
{ value: "play", label: "Play" },
{ value: "speak", label: "Speak" },
{ value: "bestiary", label: "Bestiary" },
+ { value: "beatbox", label: "Beatbox" },
]}
/>
{mode !== "bestiary" && (
@@ -102,30 +104,32 @@ function StartPrompt() {
const err = useStore((s) => s.startError);
const start = useStore((s) => s.start);
const setHold = useStore((s) => s.setHold);
- const bestiary = useStore((s) => s.mode === "bestiary");
+ const mode = useStore((s) => s.mode);
const playCall = useStore((s) => s.playCall);
const creature = useStore((s) => s.creature);
+ const setBeatPlaying = useStore((s) => s.setBeatPlaying);
if (started) return null;
+ const copy = {
+ bestiary: ["Each animal's sound comes from a simulation of its own sound source and airway.", "Start and hear a call", "Then play its calls, or hold the keys to sustain it at a pitch."],
+ beatbox: ["Every drum here is a mouth sound: lips, tongue and larynx pushing, sealing and sucking air.", "Start the beat", "Then edit the pattern, tap the pads, or hum a bass note on the keys."],
+ }[mode as "bestiary" | "beatbox"] ?? ["Every sound here is produced by simulating air moving through a throat, mouth and nose.", "Breathe in and start", "Then drag the tongue, lips or jaw, or play the keys."];
return (
<div className="start-prompt">
- <p>{bestiary ? "Each animal's sound comes from a simulation of its own sound source and airway." : "Every sound here is produced by simulating air moving through a throat, mouth and nose."}</p>
+ <p>{copy[0]}</p>
<button
className="primary large"
disabled={starting}
onClick={async () => {
await start();
const first = creatureById(creature)?.calls[0];
- if (bestiary && first) playCall(first.id);
- else if (!bestiary) setHold(true);
+ if (mode === "bestiary" && first) playCall(first.id);
+ else if (mode === "beatbox") setBeatPlaying(true);
+ else setHold(true);
}}
>
- {starting ? "Starting…" : bestiary ? "Start and hear a call" : "Breathe in and start"}
+ {starting ? "Starting…" : copy[1]}
</button>
- {err ? (
- <p className="error">Audio could not start: {err}. Reload the page and try again.</p>
- ) : (
- <p className="hint">{bestiary ? "Then play its calls, or hold the keys to sustain it at a pitch." : "Then drag the tongue, lips or jaw, or play the keys."}</p>
- )}
+ {err ? <p className="error">Audio could not start: {err}. Reload the page and try again.</p> : <p className="hint">{copy[2]}</p>}
</div>
);
}
@@ -134,6 +138,7 @@ function Deck() {
const mode = useStore((s) => s.mode);
if (mode === "speak") return <SpeakPanel />;
if (mode === "bestiary") return <BestiaryPanel />;
+ if (mode === "beatbox") return <BeatboxPanel />;
return (
<>
<section className="deck">
@@ -152,8 +157,25 @@ function Deck() {
}
function Instruments() {
- const bestiary = useStore((s) => s.mode === "bestiary");
- if (bestiary)
+ const mode = useStore((s) => s.mode);
+ if (mode === "beatbox")
+ return (
+ <aside className="instruments">
+ <figure className="instrument">
+ <figcaption>Tube, glottis to lips</figcaption>
+ <TubeView />
+ </figure>
+ <figure className="instrument">
+ <figcaption>Spectrogram</figcaption>
+ <Spectrogram />
+ </figure>
+ <figure className="instrument">
+ <figcaption>Vocal folds, slowed down</figcaption>
+ <Stroboscope />
+ </figure>
+ </aside>
+ );
+ if (mode === "bestiary")
return (
<aside className="instruments">
<figure className="instrument">
@@ -189,10 +211,12 @@ function Instruments() {
}
function Viewport() {
- const bestiary = useStore((s) => s.mode === "bestiary");
+ const mode = useStore((s) => s.mode);
+ const bestiary = mode === "bestiary";
return (
<section className="viewport" aria-label={bestiary ? "Live creature airway" : "Live vocal tract"}>
{bestiary ? <CreatureView /> : <AnatomyView />}
+ {mode === "beatbox" && <BeatOverlay />}
<StartPrompt />
<ViewToggles />
</section>
diff --git a/src/ui/components/BeatboxPanel.tsx b/src/ui/components/BeatboxPanel.tsx
new file mode 100644
index 0000000..6d596ef
--- /dev/null
+++ b/src/ui/components/BeatboxPanel.tsx
@@ -0,0 +1,189 @@
+import { useEffect, useRef, useState } from "react";
+import { useStore } from "../store.ts";
+import { engine } from "../../audio/AudioEngine.ts";
+import { BEAT_SOUNDS, BEAT_PRESETS, formatBeat, parseBeat, type Airstream } from "../../engine/phonetics/beatbox.ts";
+import { Slider, Toggle } from "./Controls.tsx";
+import { Keys } from "./Keys.tsx";
+
+const AIR: Record<Airstream, string> = {
+ pulmonic: "Breath out",
+ ejective: "Larynx piston",
+ click: "Tongue suction",
+ ingressive: "Breath in",
+ voiced: "Voice",
+};
+
+const NOTE = ["C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B"];
+const noteName = (m: number) => `${NOTE[((m % 12) + 12) % 12]}${Math.floor(m / 12) - 1}`;
+
+/** Step under the playhead, polled from telemetry (re-renders only when it changes). */
+export function useBeatStep(): number {
+ const [step, setStep] = useState(-1);
+ useEffect(() => {
+ let raf = 0;
+ const loop = () => {
+ const s = engine.latest?.beatStep ?? -1;
+ setStep((prev) => (prev === s ? prev : s));
+ raf = requestAnimationFrame(loop);
+ };
+ raf = requestAnimationFrame(loop);
+ return () => cancelAnimationFrame(raf);
+ }, []);
+ return step;
+}
+
+function Pads() {
+ const beatHit = useStore((s) => s.beatHit);
+ const [lit, setLit] = useState<string | null>(null);
+ const timer = useRef(0);
+ const hit = (id: string) => {
+ beatHit(id);
+ setLit(id);
+ clearTimeout(timer.current);
+ timer.current = window.setTimeout(() => setLit(null), 160);
+ };
+ const hitRef = useRef(hit);
+ hitRef.current = hit;
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.repeat || e.metaKey || e.ctrlKey || e.altKey) return;
+ const t = e.target as HTMLElement;
+ if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA") && (t as HTMLInputElement).type !== "range" && (t as HTMLInputElement).type !== "checkbox") return;
+ const i = "1234567890".indexOf(e.key);
+ if (i >= 0 && i < BEAT_SOUNDS.length) {
+ hitRef.current(BEAT_SOUNDS[i].id);
+ e.preventDefault();
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, []);
+ return (
+ <div className="panel pads-panel">
+ <h2>Sounds</h2>
+ <div className="pads">
+ {BEAT_SOUNDS.map((s, i) => (
+ <button key={s.id} className={`pad pad-${s.role}${lit === s.id ? " lit" : ""}`} onPointerDown={() => hit(s.id)} title={s.hint} aria-label={`${s.name}: ${s.hint}. Key ${(i + 1) % 10}`}>
+ <span className="pad-sym">{s.id}</span>
+ <span className="pad-name">{s.name}</span>
+ <span className="pad-air">{AIR[s.airstream]}</span>
+ <span className="pad-key" aria-hidden="true">
+ {(i + 1) % 10}
+ </span>
+ </button>
+ ))}
+ </div>
+ <p className="dim">Pads play a sound as soon as the mouth can shape it, about a tenth of a second. Keys hum a bass note under the beat.</p>
+ </div>
+ );
+}
+
+function Sequencer() {
+ const beat = useStore((s) => s.beat);
+ const toggle = useStore((s) => s.toggleBeatStep);
+ const setTempo = useStore((s) => s.setBeatTempo);
+ const setPlaying = useStore((s) => s.setBeatPlaying);
+ const setSteps = useStore((s) => s.setBeatSteps);
+ const loadPreset = useStore((s) => s.loadBeatPreset);
+ const mic = useStore((s) => s.mic);
+ const setMic = useStore((s) => s.setMic);
+ const now = useBeatStep();
+ const [text, setText] = useState(() => formatBeat(beat.steps));
+ const editing = useRef(false);
+ useEffect(() => {
+ if (!editing.current) setText(formatBeat(beat.steps));
+ }, [beat.steps]);
+ const n = beat.steps.length;
+ return (
+ <div className="panel seq-panel">
+ <div className="transport">
+ <button className={`primary play${beat.playing ? " on" : ""}`} onClick={() => setPlaying(!beat.playing)} aria-pressed={beat.playing}>
+ {beat.playing ? "Stop" : "Play beat"}
+ </button>
+ <div className="transport-sliders">
+ <Slider label="Tempo" value={beat.bpm} min={60} max={180} onChange={(v) => setTempo({ bpm: Math.round(v) })} format={(v) => `${Math.round(v)} bpm`} />
+ <Slider label="Swing" value={beat.swing} min={0} max={0.6} onChange={(v) => setTempo({ swing: v })} format={(v) => `${Math.round(v * 100)} %`} />
+ </div>
+ <Toggle label="Close mic" checked={mic} onChange={setMic} />
+ </div>
+ <div className="examples presets" role="group" aria-label="Example beats">
+ {BEAT_PRESETS.map((p) => (
+ <button key={p.name} className={`chip${beat.preset === p.name ? " on" : ""}`} onClick={() => loadPreset(p.name)}>
+ {p.name}
+ </button>
+ ))}
+ </div>
+ <div className="seq-grid" style={{ "--steps": n } as React.CSSProperties} role="grid" aria-label="Beat pattern: one sound per step">
+ {BEAT_SOUNDS.map((s) => (
+ <div className="seq-row" role="row" key={s.id}>
+ <span className="seq-label" role="rowheader">
+ <b>{s.id}</b> {s.name}
+ </span>
+ {beat.steps.map((st, i) => {
+ const on = st?.id === s.id;
+ return (
+ <button
+ key={i}
+ role="gridcell"
+ className={`cell${on ? " on" : ""}${i === now ? " now" : ""}${i % 4 === 0 ? " downbeat" : ""}`}
+ onClick={() => toggle(i, s.id)}
+ aria-pressed={on}
+ aria-label={`${s.name}, step ${i + 1}`}
+ >
+ {on && s.id === "m" && st?.note !== undefined ? <span className="cell-note">{noteName(st.note)}</span> : null}
+ </button>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ <label className="sbn">
+ <span className="dim">Beat as text: B kick, t hat, Pf snare, K rimshot, ^K inward, ! click, m hum (m:43 sets its note), . rest</span>
+ <input
+ value={text}
+ spellCheck={false}
+ onFocus={() => (editing.current = true)}
+ onBlur={() => {
+ editing.current = false;
+ setText(formatBeat(beat.steps));
+ }}
+ onChange={(e) => {
+ setText(e.target.value);
+ const steps = parseBeat(e.target.value);
+ if (steps.length) setSteps(steps);
+ }}
+ />
+ </label>
+ </div>
+ );
+}
+
+export function BeatboxPanel() {
+ return (
+ <>
+ <section className="beatbox">
+ <Pads />
+ <Sequencer />
+ </section>
+ <footer className="keys-bar">
+ <Keys />
+ </footer>
+ </>
+ );
+}
+
+/** The symbol of the sound being made, large over the anatomy, fading after each hit. */
+export function BeatOverlay() {
+ const steps = useStore((s) => s.beat.steps);
+ const playing = useStore((s) => s.beat.playing);
+ const now = useBeatStep();
+ const cell = now >= 0 ? steps[now] : null;
+ if (!playing || !cell) return null;
+ const s = BEAT_SOUNDS.find((x) => x.id === cell.id);
+ return (
+ <div className="beat-overlay" aria-hidden="true" key={now}>
+ <span className="beat-sym">{cell.id}</span>
+ <span className="beat-name">{s?.name}</span>
+ </div>
+ );
+}
diff --git a/src/ui/store.ts b/src/ui/store.ts
index 7b5a6bc..cc82659 100644
--- a/src/ui/store.ts
+++ b/src/ui/store.ts
@@ -5,10 +5,20 @@ import { NEUTRAL, restTip, type HumanArtic } from "../engine/anatomy/human.ts";
import type { BodyName } from "../worklet/protocol.ts";
import { creatureById } from "../engine/creatures/index.ts";
import type { ParamDef } from "../engine/creatures/types.ts";
+import { BEAT_PRESETS, BASS_NOTE, beatReady, parseBeat, type BeatStep } from "../engine/phonetics/beatbox.ts";
export const DEFAULT_F0: Record<BodyName, number> = { male: 110, female: 205, child: 260 };
-export type Mode = "play" | "speak" | "bestiary";
+export type Mode = "play" | "speak" | "bestiary" | "beatbox";
+
+export interface BeatState {
+ steps: (BeatStep | null)[];
+ bpm: number;
+ swing: number;
+ playing: boolean;
+ /** preset the pattern came from (null once edited) */
+ preset: string | null;
+}
export interface ViewOptions {
pressure: boolean;
@@ -41,6 +51,19 @@ interface State {
/** what the keys do in the bestiary: hold the voice at a pitch (null) or trigger this call */
keyCall: string | null;
setKeyCall: (id: string | null) => void;
+ beat: BeatState;
+ /** close-mic sound (proximity bass + compression) in beatbox mode */
+ mic: boolean;
+ /** hum note for new hum steps: follows the last key played */
+ bassNote: number;
+ setBeatSteps: (steps: (BeatStep | null)[], preset?: string | null) => void;
+ /** one sound per step: set it, or clear the step if that sound is already there */
+ toggleBeatStep: (i: number, id: string) => void;
+ setBeatTempo: (v: { bpm?: number; swing?: number }) => void;
+ setBeatPlaying: (on: boolean) => void;
+ loadBeatPreset: (name: string) => void;
+ beatHit: (id: string) => void;
+ setMic: (on: boolean) => void;
start: () => Promise<void>;
setBody: (b: BodyName) => void;
setSource: (v: Partial<VoiceSource>) => void;
@@ -74,6 +97,8 @@ function updateGate(s: { hold: boolean; heldNotes: number[]; mode: Mode; keyCall
let startPromise: Promise<void> | null = null;
+const FIRST_BEAT = BEAT_PRESETS[0];
+
export const useStore = create<State>((set, get) => ({
started: false,
starting: false,
@@ -101,6 +126,16 @@ export const useStore = create<State>((set, get) => ({
const s = get();
engine.setCreature(m === "bestiary" ? s.creature : "human", s.cparams[s.creature]);
}
+ if (prev === "beatbox") {
+ get().setBeatPlaying(false);
+ engine.setMic(false);
+ }
+ if (m === "beatbox") {
+ // a beatboxer waits with the jaw nearly closed; the sounds bring their own breath
+ set({ hold: false });
+ get().setArtic(beatReady(get().body));
+ engine.setMic(get().mic);
+ }
updateGate(get());
},
creature: "songbird",
@@ -110,6 +145,53 @@ export const useStore = create<State>((set, get) => ({
set({ keyCall: id, heldNotes: [] });
updateGate(get());
},
+ beat: { steps: parseBeat(FIRST_BEAT.text), bpm: FIRST_BEAT.bpm, swing: FIRST_BEAT.swing, playing: false, preset: FIRST_BEAT.name },
+ mic: true,
+ bassNote: BASS_NOTE,
+ setBeatSteps: (steps, preset = null) => {
+ set((s) => ({ beat: { ...s.beat, steps, preset } }));
+ engine.setBeat({ steps });
+ },
+ toggleBeatStep: (i, id) => {
+ const steps = get().beat.steps.slice();
+ steps[i] = steps[i]?.id === id ? null : id === "m" ? { id, note: get().bassNote } : { id };
+ get().setBeatSteps(steps);
+ },
+ setBeatTempo: (v) => {
+ set((s) => ({ beat: { ...s.beat, ...v } }));
+ engine.setBeat(v);
+ },
+ setBeatPlaying: (on) => {
+ if (on === get().beat.playing) return;
+ set((s) => ({ beat: { ...s.beat, playing: on } }));
+ if (!on) {
+ engine.setBeat({ playing: false });
+ return;
+ }
+ void get()
+ .start()
+ .then(() => {
+ const b = get().beat;
+ if (get().started && b.playing) engine.setBeat({ steps: b.steps, bpm: b.bpm, swing: b.swing, playing: true });
+ });
+ },
+ loadBeatPreset: (name) => {
+ const p = BEAT_PRESETS.find((x) => x.name === name);
+ if (!p) return;
+ get().setBeatSteps(parseBeat(p.text), p.name);
+ get().setBeatTempo({ bpm: p.bpm, swing: p.swing });
+ },
+ beatHit: (id) => {
+ void get()
+ .start()
+ .then(() => {
+ if (get().started) engine.beatHit(id, id === "m" ? get().bassNote : undefined);
+ });
+ },
+ setMic: (on) => {
+ set({ mic: on });
+ if (get().mode === "beatbox") engine.setMic(on);
+ },
setCreature: (id) => {
if (id === get().creature) return;
set({ creature: id, keyCall: null, heldNotes: [] });
@@ -142,6 +224,10 @@ export const useStore = create<State>((set, get) => ({
engine.setSource(s.source);
engine.setArtic(s.artic, s.tipFree);
if (s.mode === "bestiary") engine.setCreature(s.creature, s.cparams[s.creature]);
+ if (s.mode === "beatbox") {
+ engine.setMic(s.mic);
+ engine.setBeat({ steps: s.beat.steps, bpm: s.beat.bpm, swing: s.beat.swing, playing: s.beat.playing });
+ }
updateGate(s);
set({ started: true, starting: false });
} catch (e) {
@@ -182,6 +268,11 @@ export const useStore = create<State>((set, get) => ({
const f = pp ? creatureKeyHz(midi, pp) : undefined;
if (s.keyCall) s.playCall(s.keyCall, f);
else if (pp && f) s.setCParam(pp.key, f);
+ } else if (s.mode === "beatbox") {
+ // keys hum a bass note under the beat (lips shut, nose open); new hum steps take it too
+ set({ bassNote: midi });
+ if (held.length === 1) s.setArtic({ lipAp: -0.25, velum: 0.9 });
+ s.setSource({ f0: midiToHz(midi) });
} else s.setSource({ f0: midiToHz(midi) });
updateGate(get());
},
@@ -189,6 +280,7 @@ export const useStore = create<State>((set, get) => ({
const held = get().heldNotes.filter((n) => n !== midi);
set({ heldNotes: held });
const s = get();
+ if (s.mode === "beatbox" && !held.length) s.setArtic({ lipAp: beatReady(s.body).lipAp, velum: 0 });
if (held.length) {
// fall back to the most recent note still held (legato)
const last = held[held.length - 1];
diff --git a/src/ui/styles.css b/src/ui/styles.css
index 0e212a3..5dd5320 100644
--- a/src/ui/styles.css
+++ b/src/ui/styles.css
@@ -727,6 +727,241 @@ button.ghost {
row-gap: 4px;
}
+/* ---------- beatbox */
+.beatbox {
+ display: grid;
+ grid-template-columns: minmax(250px, 0.75fr) minmax(460px, 2fr);
+ gap: 10px;
+}
+
+.pads-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.pads {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(92px, 1fr));
+ gap: 6px;
+}
+
+.pad {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 1px;
+ padding: 7px 9px 8px;
+ min-height: 74px;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-s);
+ background: var(--black);
+ text-align: left;
+ cursor: pointer;
+ touch-action: manipulation;
+ user-select: none;
+}
+
+.pad:hover {
+ border-color: var(--text-dim);
+}
+
+.pad.lit,
+.pad:active {
+ border-color: #ffd15c;
+ box-shadow: inset 0 0 0 1px #ffd15c, 0 0 18px rgba(240, 88, 28, 0.45);
+}
+
+.pad-sym {
+ font-size: 22px;
+ font-weight: 750;
+ font-stretch: 115%;
+ line-height: 1.05;
+}
+
+.pad-name {
+ font-size: 13px;
+ font-weight: 550;
+}
+
+.pad-air {
+ font-size: 11.5px;
+ font-stretch: 87%;
+ color: var(--text-dim);
+}
+
+.pad-key {
+ position: absolute;
+ top: 6px;
+ right: 8px;
+ font-size: 11px;
+ color: var(--text-dim);
+ opacity: 0.7;
+}
+
+.pads-panel .dim {
+ margin: 2px 0 0;
+}
+
+.seq-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ min-width: 0;
+}
+
+.transport {
+ display: flex;
+ align-items: center;
+ gap: 18px;
+ flex-wrap: wrap;
+}
+
+.transport .play {
+ min-width: 104px;
+}
+
+.transport .play.on {
+ background: #ffd15c;
+}
+
+.transport-sliders {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 4px 18px;
+ flex: 1;
+ min-width: 240px;
+}
+
+.seq-grid {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ overflow-x: auto;
+}
+
+.seq-row {
+ display: grid;
+ grid-template-columns: 112px repeat(var(--steps), minmax(14px, 1fr));
+ gap: 3px;
+ align-items: stretch;
+}
+
+.seq-label {
+ font-size: 12.5px;
+ font-stretch: 87%;
+ color: var(--text-dim);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ align-self: center;
+}
+
+.seq-label b {
+ display: inline-block;
+ min-width: 2.1em;
+ color: var(--text);
+ font-weight: 650;
+}
+
+.cell {
+ position: relative;
+ height: 22px;
+ border: 0;
+ border-radius: 3px;
+ background: #151a1d;
+ cursor: pointer;
+ padding: 0;
+}
+
+.cell.downbeat {
+ background: #2b3338;
+}
+
+.cell:hover {
+ background: #2c3438;
+}
+
+.cell.on {
+ background: #cfd3d5;
+}
+
+.cell.now {
+ box-shadow: inset 0 0 0 1px var(--caliper);
+}
+
+.cell.on.now {
+ background: #ffd15c;
+ box-shadow: 0 0 10px rgba(240, 88, 28, 0.7);
+}
+
+.cell-note {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ font-size: 9.5px;
+ font-weight: 650;
+ color: #1d1a10;
+ line-height: 1;
+}
+
+.sbn {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.sbn input {
+ width: 100%;
+ background: var(--black);
+ color: var(--text);
+ border: 1px solid var(--line);
+ border-radius: var(--radius-s);
+ padding: 7px 10px;
+ font: inherit;
+ font-size: 15px;
+ letter-spacing: 0.02em;
+}
+
+.beat-overlay {
+ position: absolute;
+ right: 22px;
+ bottom: 60px;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-end;
+ pointer-events: none;
+ animation: beat-fade 420ms ease-out forwards;
+}
+
+.beat-sym {
+ font-size: clamp(48px, 9vw, 112px);
+ font-weight: 800;
+ font-stretch: 125%;
+ line-height: 0.9;
+ color: #ffd15c;
+ text-shadow: 0 0 24px rgba(240, 88, 28, 0.55);
+}
+
+.beat-name {
+ font-size: 14px;
+ color: var(--text-dim);
+ margin-top: 4px;
+}
+
+@keyframes beat-fade {
+ from {
+ opacity: 1;
+ transform: scale(1.04);
+ }
+ to {
+ opacity: 0.18;
+ transform: scale(1);
+ }
+}
+
/* ---------- keys */
.keys-bar {
background: var(--inset);
@@ -805,6 +1040,9 @@ button.ghost {
.creature-params {
grid-column: 1 / -1;
}
+ .beatbox {
+ grid-template-columns: 1fr;
+ }
}
@media (max-width: 900px) {
@@ -829,9 +1067,30 @@ button.ghost {
}
.deck,
.speak,
- .bestiary {
+ .bestiary,
+ .beatbox {
order: 2;
}
+ .seq-row {
+ grid-template-columns: 34px repeat(var(--steps), minmax(12px, 1fr));
+ gap: 2px;
+ }
+ .seq-label {
+ font-size: 0;
+ }
+ .seq-label b {
+ font-size: 12.5px;
+ min-width: 0;
+ }
+ .cell {
+ height: 20px;
+ }
+ .pads {
+ grid-template-columns: repeat(auto-fill, minmax(74px, 1fr));
+ }
+ .pad {
+ min-height: 64px;
+ }
.keys-bar {
order: 3;
}
@@ -841,10 +1100,6 @@ button.ghost {
.tagline {
display: none;
}
- .viewport {
- min-height: 360px;
- aspect-ratio: 1 / 1;
- }
.instruments {
grid-template-columns: 1fr;
}
@@ -862,17 +1117,30 @@ button.ghost {
.specimens {
grid-template-columns: repeat(2, 1fr);
}
+ .viewport {
+ display: flex;
+ flex-direction: column;
+ aspect-ratio: auto;
+ min-height: 0;
+ }
+ .anatomy,
+ .creature-canvas {
+ position: relative;
+ inset: auto;
+ width: 100%;
+ aspect-ratio: 1 / 1;
+ height: auto;
+ }
.view-toggles {
- top: auto;
- bottom: 8px;
- left: 8px;
- right: 8px;
+ position: static;
flex-direction: row;
flex-wrap: wrap;
- gap: 4px 12px;
- padding: 6px 8px;
- background: rgba(0, 0, 0, 0.55);
- border-radius: var(--radius-s);
+ gap: 4px 14px;
+ padding: 8px 10px 10px;
+ }
+ .beat-overlay {
+ bottom: auto;
+ top: calc(100vw - 150px);
}
.keys {
height: 64px;
@@ -883,4 +1151,7 @@ button.ghost {
* {
scroll-behavior: auto !important;
}
+ .beat-overlay {
+ animation: none;
+ }
}
diff --git a/src/worklet/processor.ts b/src/worklet/processor.ts
index a1bcc61..026d441 100644
--- a/src/worklet/processor.ts
+++ b/src/worklet/processor.ts
@@ -7,6 +7,7 @@ import { BODY_MALE, BODY_FEMALE, BODY_CHILD, type HumanBody } from "../engine/an
import type { ToWorklet, FromWorklet, BodyName } from "./protocol.ts";
import { CreatureVoice } from "../engine/creatures/voice.ts";
import { creatureById } from "../engine/creatures/index.ts";
+import { BeatPlayer } from "../engine/control/beatPlayer.ts";
// Minimal AudioWorkletGlobalScope typings
declare const sampleRate: number;
@@ -32,6 +33,7 @@ class ChimeraProcessor extends AudioWorkletProcessor {
private pendingCreatureParams: Record<string, number> = {};
private pendingCall: { id: string; pitch?: number; amp?: number } | null = null;
private gateLevel = 0;
+ private beat = new BeatPlayer();
constructor() {
super();
@@ -102,6 +104,23 @@ class ChimeraProcessor extends AudioWorkletProcessor {
case "stopSpeech":
this.voice.cancelScore();
break;
+ case "beat": {
+ const b = this.beat;
+ if (m.steps) b.steps = m.steps.slice(0, 128);
+ if (m.bpm !== undefined || m.swing !== undefined) b.setTempo(m.bpm ?? b.bpm, m.swing ?? b.swing);
+ if (m.playing === true && !b.playing) b.start(this.voice.clock);
+ if (m.playing === false && b.playing) {
+ b.stop();
+ // hits already scheduled within the horizon would still sound
+ this.voice.cancelScore();
+ }
+ break;
+ }
+ case "beatHit": {
+ const hit = this.voice.clock + BeatPlayer.leadIn(m.id, this.body);
+ this.voice.schedule(this.beat.gestures({ id: m.id, note: m.note, accent: m.accent }, hit, 0.18));
+ break;
+ }
}
}
@@ -114,6 +133,9 @@ class ChimeraProcessor extends AudioWorkletProcessor {
this.body = this.pendingBody;
this.pendingBody = null;
this.voice = this.makeVoice(this.body);
+ // the new voice's clock starts at zero: keep the beat's phase across the switch
+ this.beat.body = this.body;
+ this.beat.rebase(this.voice.clock - prev.clock);
this.voice.setSource({ ...prev.source, f0: DEFAULT_F0[this.body] });
this.voice.setArticulation({ ...prev.artic.target }, prev.artic.tipFree);
this.voice.setGate(prev.gate > 0.5 ? 1 : 0);
@@ -136,6 +158,7 @@ class ChimeraProcessor extends AudioWorkletProcessor {
this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr, creature: this.creature ? this.creature.def.id : "human" });
}
const ch0 = out[0];
+ if (!this.creature) this.beat.tick(this.voice.clock, (gs) => this.voice.schedule(gs));
const t0 = Date.now();
try {
if (this.creature) this.creature.render(ch0, 0, ch0.length);
@@ -150,7 +173,7 @@ class ChimeraProcessor extends AudioWorkletProcessor {
this.load += 0.05 * (dt / budget - this.load);
if (this.telemetryOn && ++this.blocks % 6 === 0) {
if (this.creature) this.post({ type: "ctelemetry", t: this.creature.telemetry(), load: this.load });
- else this.post({ type: "telemetry", t: this.voice.telemetry(), load: this.load, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr });
+ else this.post({ type: "telemetry", t: this.voice.telemetry(), load: this.load, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr, beatStep: this.beat.stepAt(this.voice.clock) });
}
return true;
}
diff --git a/src/worklet/protocol.ts b/src/worklet/protocol.ts
index ba8ce90..f4b60a3 100644
--- a/src/worklet/protocol.ts
+++ b/src/worklet/protocol.ts
@@ -4,6 +4,7 @@ import type { VoiceSource, VoiceTelemetry } from "../engine/voice/humanVoice.ts"
import type { Segment, PlannedSegment } from "../engine/phonetics/planner.ts";
import type { Gesture } from "../engine/control/score.ts";
import type { CreatureTelemetry } from "../engine/creatures/voice.ts";
+import type { BeatStep } from "../engine/phonetics/beatbox.ts";
export interface PhraseMsg {
segments: Segment[];
@@ -26,7 +27,11 @@ export type ToWorklet =
| { type: "creature"; id: string; params?: Record<string, number> }
| { type: "cparams"; values: Record<string, number> }
| { type: "call"; id: string; pitch?: number; amp?: number }
- | { type: "stopCall" };
+ | { type: "stopCall" }
+ /** beatbox sequencer: any subset of its state */
+ | { type: "beat"; steps?: (BeatStep | null)[]; bpm?: number; swing?: number; playing?: boolean }
+ /** play one beatbox sound as soon as the mouth can make it */
+ | { type: "beatHit"; id: string; note?: number; accent?: number };
export interface TelemetryMessage {
type: "telemetry";
@@ -36,6 +41,8 @@ export interface TelemetryMessage {
body: BodyName;
nPh: number;
nOr: number;
+ /** beatbox step under the playhead (−1 when the sequencer is stopped) */
+ beatStep: number;
}
export interface PlannedMessage {
diff --git a/tests/beatbox.test.ts b/tests/beatbox.test.ts
new file mode 100644
index 0000000..1df196b
--- /dev/null
+++ b/tests/beatbox.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, test } from "bun:test";
+import { BEAT_PRESETS, BEAT_SOUNDS, formatBeat, parseBeat } from "../src/engine/phonetics/beatbox.ts";
+import { BeatPlayer } from "../src/engine/control/beatPlayer.ts";
+import type { Gesture } from "../src/engine/control/score.ts";
+
+/** Hit time of each scheduled sound: the planned hit is where its gestures were shifted to. */
+function run(p: BeatPlayer, from: number, to: number, dt = 128 / 48000): { t: number; label: string }[] {
+ const hits: { t: number; label: string }[] = [];
+ for (let clock = from; clock < to; clock += dt)
+ p.tick(clock, (gs: Gesture[]) => {
+ const ref = p.gestures({ id: gs[0].label === "m" ? "m" : (gs[0].label as string) }, 0);
+ hits.push({ t: gs[0].t0 - ref[0].t0, label: gs[0].label as string });
+ });
+ return hits;
+}
+
+describe("beat notation", () => {
+ test("parses symbols, rests, notes, accents and bar lines", () => {
+ const s = parseBeat("B . t | Pf m:43 ^K> -");
+ expect(s.map((x) => x?.id ?? null)).toEqual(["B", null, "t", "Pf", "m", "^K", null]);
+ expect(s[4]?.note).toBe(43);
+ expect(s[5]?.accent).toBeGreaterThan(1);
+ });
+ test("format and parse round-trip every preset", () => {
+ for (const p of BEAT_PRESETS) {
+ const steps = parseBeat(p.text);
+ expect(steps.length).toBe(16);
+ expect(parseBeat(formatBeat(steps))).toEqual(steps);
+ }
+ });
+ test("every sound builds gestures that start before and end after its hit", () => {
+ for (const s of BEAT_SOUNDS)
+ for (const body of ["male", "female", "child"]) {
+ const gs = s.build(body, { f0: 82, len: 0.15, accent: 1 });
+ expect(gs.length).toBeGreaterThan(0);
+ expect(Math.min(...gs.map((g) => g.t0 - g.rampIn))).toBeLessThan(0);
+ expect(Math.max(...gs.map((g) => g.t1 + g.rampOut))).toBeGreaterThan(0);
+ // everything a sound needs fits inside the sequencer's look-ahead
+ expect(BeatPlayer.leadIn(s.id, body)).toBeLessThan(new BeatPlayer().horizon);
+ }
+ });
+});
+
+describe("beat player", () => {
+ test("schedules each step once, on the grid, with swing on the off-beats", () => {
+ const p = new BeatPlayer();
+ p.steps = parseBeat("B t B t");
+ p.setTempo(120, 0.5);
+ p.start(0);
+ const hits = run(p, 0, 2.2);
+ const step = 60 / 120 / 4;
+ // 2 s of sixteenths at 120 bpm = 16 steps, starting one horizon in
+ expect(hits.length).toBeGreaterThanOrEqual(15);
+ hits.slice(0, 8).forEach((h, n) => {
+ const want = p.horizon + n * step + (n % 2 ? 0.25 * step : 0);
+ expect(Math.abs(h.t - want)).toBeLessThan(1e-9);
+ });
+ });
+ test("tempo changes keep the next step's time (no jump)", () => {
+ const p = new BeatPlayer();
+ p.steps = parseBeat("t t t t");
+ p.setTempo(100, 0);
+ p.start(0);
+ const before = run(p, 0, 0.6);
+ const last = before[before.length - 1].t;
+ p.setTempo(160, 0);
+ const after = run(p, 0.6, 1.2);
+ const gap = after[0].t - last;
+ // the first step after the change is spaced by at most one old step, then the new tempo
+ expect(gap).toBeGreaterThan(0);
+ expect(gap).toBeLessThanOrEqual(60 / 100 / 4 + 1e-9);
+ expect(after[2].t - after[1].t).toBeCloseTo(60 / 160 / 4, 9);
+ });
+ test("reports the step under the playhead and nothing when stopped", () => {
+ const p = new BeatPlayer();
+ p.steps = parseBeat("B . t .");
+ p.setTempo(120, 0);
+ expect(p.stepAt(1)).toBe(-1);
+ p.start(0);
+ expect(p.stepAt(p.horizon + 0.01)).toBe(0);
+ expect(p.stepAt(p.horizon + 3 * 0.125 + 0.01)).toBe(3);
+ expect(p.stepAt(p.horizon + 4 * 0.125 + 0.01)).toBe(0);
+ p.stop();
+ expect(p.stepAt(1)).toBe(-1);
+ });
+});
diff --git a/tools/e2e.ts b/tools/e2e.ts
index f4a738c..30a650d 100644
--- a/tools/e2e.ts
+++ b/tools/e2e.ts
@@ -94,6 +94,28 @@ async function run(viewport: { width: number; height: number }, tag: string) {
});
await page.keyboard.up("g");
logs.push(`[${tag}] held key: ${JSON.stringify(held)}`);
+ // beatbox: preset, play, playhead + level from telemetry, a pad, stop
+ await page.getByRole("radio", { name: "Beatbox" }).click();
+ await page.waitForTimeout(300);
+ await page.getByRole("button", { name: "Breakbeat" }).click();
+ await page.getByRole("button", { name: "Play beat" }).click();
+ const beatSamples: { step: number; rms: number }[] = [];
+ for (let i = 0; i < 8; i++) {
+ await page.waitForTimeout(250);
+ beatSamples.push(
+ await page.evaluate(() => {
+ // @ts-expect-error debug handle
+ const t = window.__chimeraEngine?.latest;
+ return { step: t?.beatStep ?? -2, rms: t?.t?.outRms ?? -1 };
+ }),
+ );
+ }
+ await page.screenshot({ path: `${outDir}/${tag}-6-beatbox.png`, fullPage: tag !== "desktop" });
+ logs.push(`[${tag}] beatbox steps ${beatSamples.map((b) => b.step).join(",")} rms ${beatSamples.map((b) => b.rms.toFixed(3)).join(",")}`);
+ await page.locator(".pad").first().dispatchEvent("pointerdown");
+ await page.waitForTimeout(300);
+ await page.getByRole("button", { name: "Stop" }).click();
+ await page.waitForTimeout(300);
// back to the human voice
await page.getByRole("radio", { name: "Play" }).click();
await page.waitForTimeout(600);
@@ -110,4 +132,4 @@ await run({ width: 1440, height: 980 }, "desktop");
await run({ width: 390, height: 844 }, "mobile");
await browser.close();
console.log("console errors:", errors.length ? "\n" + errors.join("\n") : "none");
-console.log(logs.filter((l) => /load|warn|transcription|creature|held|back to/i.test(l)).slice(0, 40).join("\n"));
+console.log(logs.filter((l) => /load|warn|transcription|creature|held|back to|beatbox/i.test(l)).slice(0, 40).join("\n"));
diff --git a/tools/render-beatbox.ts b/tools/render-beatbox.ts
new file mode 100644
index 0000000..8754d72
--- /dev/null
+++ b/tools/render-beatbox.ts
@@ -0,0 +1,84 @@
+/**
+ * Render the beatbox kit through the real-time voice.
+ * - each sound alone: acoustic onset relative to the planned hit (calibrates `latency`), peak,
+ * and a spectrogram strip
+ * - a preset pattern (two bars) as WAV + spectrogram with step marks
+ * Usage: bun tools/render-beatbox.ts outdir [preset name] [male|female|child]
+ */
+import { mkdirSync } from "node:fs";
+import { HumanVoice } from "../src/engine/voice/humanVoice.ts";
+import { BODY_MALE, BODY_FEMALE, BODY_CHILD } from "../src/engine/anatomy/human.ts";
+import { BEAT_SOUNDS, BEAT_PRESETS, beatReady, parseBeat } from "../src/engine/phonetics/beatbox.ts";
+import { BeatPlayer } from "../src/engine/control/beatPlayer.ts";
+import { writeWav } from "./lib/wav.ts";
+import { renderSpectrogram } from "./lib/spectrogram.ts";
+
+const outDir = process.argv[2] ?? "out/beatbox";
+const presetName = process.argv[3] ?? "Boots and cats";
+const bodyName = (process.argv[4] ?? "male") as "male" | "female" | "child";
+const body = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD }[bodyName];
+mkdirSync(outDir, { recursive: true });
+const FS = 48000;
+
+function voice(): HumanVoice {
+ const v = new HumanVoice({ fsOut: FS, body });
+ v.setArticulation(beatReady(bodyName));
+ v.setSource({ f0: 100, voiced: true, pressure: 8 });
+ v.setGate(0);
+ return v;
+}
+
+// ---- each sound alone
+const player = new BeatPlayer();
+player.body = bodyName;
+const rows: string[] = [];
+const strip = new Float32Array(Math.round(FS * 0.5 * BEAT_SOUNDS.length));
+BEAT_SOUNDS.forEach((s, idx) => {
+ const v = voice();
+ const hit = 0.25;
+ v.schedule(player.gestures({ id: s.id }, hit, 0.15));
+ const N = Math.round(FS * 0.5);
+ const out = new Float32Array(N);
+ for (let i = 0; i < N; i += 128) v.render(out, i, Math.min(128, N - i));
+ // the event: its peak within [hit − 30 ms, hit + 80 ms]; onset = first sample from hit − 40 ms
+ // that reaches a quarter of that peak
+ let pk = 0;
+ for (let i = Math.round((hit - 0.03) * FS); i < Math.round((hit + 0.08) * FS); i++) pk = Math.max(pk, Math.abs(out[i]));
+ let on = Math.round(hit * FS);
+ for (let i = Math.round((hit - 0.04) * FS); i < Math.round((hit + 0.08) * FS); i++) if (Math.abs(out[i]) > 0.25 * pk) { on = i; break; }
+ // energy before the hit (set-up noise) relative to the hit
+ let pre = 0;
+ for (let i = Math.round((hit - 0.15) * FS); i < Math.round((hit - 0.04) * FS); i++) pre = Math.max(pre, Math.abs(out[i]));
+ // what follows: level 60–150 ms after the hit (unwanted voicing shows up here)
+ let tail = 0;
+ for (let i = Math.round((hit + 0.06) * FS); i < Math.round((hit + 0.15) * FS); i++) tail = Math.max(tail, Math.abs(out[i]));
+ rows.push(`${s.id.padEnd(4)} ${s.name.padEnd(13)} onset ${((on / FS - hit) * 1000).toFixed(1).padStart(6)} ms peak ${pk.toFixed(3)} set-up ${(20 * Math.log10(Math.max(1e-6, pre) / pk)).toFixed(1)} dB tail ${(20 * Math.log10(Math.max(1e-6, tail) / pk)).toFixed(1)} dB lead-in ${(BeatPlayer.leadIn(s.id, bodyName) * 1000).toFixed(0)} ms`);
+ strip.set(out, idx * N);
+ writeWav(`${outDir}/${s.id.replace(/[^A-Za-z]/g, "_")}.wav`, [out], FS);
+});
+console.log(rows.join("\n"));
+renderSpectrogram(`${outDir}/kit.png`, strip, FS, { title: `kit (${bodyName}): ${BEAT_SOUNDS.map((s) => s.id).join(" ")}`.replace(/[^\x20-\x7e]/g, "?"), maxFreq: 12000, windowMs: 4, marks: BEAT_SOUNDS.map((_, i) => ({ t: i * 0.5 + 0.25, label: "" })) });
+writeWav(`${outDir}/kit.wav`, [strip], FS);
+
+// ---- a pattern, two bars, through the sequencer exactly as the worklet runs it
+const preset = BEAT_PRESETS.find((p) => p.name.toLowerCase() === presetName.toLowerCase()) ?? BEAT_PRESETS[0];
+const v = voice();
+const seq = new BeatPlayer();
+seq.body = bodyName;
+seq.steps = parseBeat(preset.text);
+seq.setTempo(preset.bpm, preset.swing);
+seq.start(v.clock);
+const bars = 2;
+const total = Math.round(FS * (seq.horizon + bars * seq.steps.length * seq.stepDur + 0.3));
+const out = new Float32Array(total);
+for (let i = 0; i < total; i += 128) {
+ seq.tick(v.clock, (gs) => v.schedule(gs));
+ v.render(out, i, Math.min(128, total - i));
+}
+let pk = 0;
+for (const x of out) pk = Math.max(pk, Math.abs(x));
+const slug = preset.name.toLowerCase().replace(/[^a-z]+/g, "-");
+writeWav(`${outDir}/${slug}.wav`, [out], FS);
+const marks = Array.from({ length: bars * seq.steps.length }, (_, n) => ({ t: seq.horizon + n * seq.stepDur + (n % 2 ? seq.swing * 0.5 * seq.stepDur : 0), label: "" }));
+renderSpectrogram(`${outDir}/${slug}.png`, out, FS, { title: `${preset.name} ${preset.bpm} bpm`, maxFreq: 12000, windowMs: 4, marks });
+console.log(`pattern "${preset.name}": ${(total / FS).toFixed(2)} s, peak ${pk.toFixed(3)} -> ${outDir}/${slug}.wav`);