Skip to content

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

Rust

Sing mode: lyrics on keys (vocaloid-style), demo songs, piano roll, MIDI keyboards

Jameson Hodge9d7d1e1f9f06
diff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.ts
index fe233fc..640c604 100644
--- a/src/audio/AudioEngine.ts
+++ b/src/audio/AudioEngine.ts
@@ -22,6 +22,8 @@ export class AudioEngine {
private micIn: AudioNode | null = null;
private micOn = false;
latest: TelemetryMessage | null = null;
+ /** performance.now() when `latest` arrived */
+ private latestAt = 0;
latestCreature: CreatureTelemetryMessage | null = null;
/** load of the most recent telemetry of either kind */
load = 0;
@@ -39,6 +41,12 @@ export class AudioEngine {
private speakId = 0;
error: string | null = null;
+ /** The human voice's clock now (s), extrapolated from the latest telemetry; null if none. */
+ voiceClock(): number | null {
+ if (!this.latest) return null;
+ return this.latest.t.clock + Math.min(0.25, (performance.now() - this.latestAt) / 1000);
+ }
+
get running(): boolean {
return !!this.ctx && this.ctx.state === "running";
}
@@ -97,6 +105,7 @@ export class AudioEngine {
const m = e.data;
if (m.type === "telemetry") {
this.latest = m;
+ this.latestAt = performance.now();
this.latestCreature = null;
this.load = m.load;
for (const l of this.listeners) l(m);
diff --git a/src/engine/voice/humanVoice.ts b/src/engine/voice/humanVoice.ts
index a552bb7..3299998 100644
--- a/src/engine/voice/humanVoice.ts
+++ b/src/engine/voice/humanVoice.ts
@@ -323,6 +323,9 @@ export class HumanVoice {
const tau = gateGoal > this.gate ? 0.025 : this.scoreBreathHold > 0 ? 0.02 : 0.07;
this.gate += (gateGoal - this.gate) * (1 - Math.exp(-dt / tau));
this.pLung = this.source.pressure * CM_H2O * this.gate;
+ // vocal effort follows the pressure actually applied: a harder breath (a louder sung note)
+ // gives wider, sharper-closing pulses, as in real phonation, not just more flow
+ this.glottis.params.effort = clamp((Math.abs(this.source.pressure * this.gate) - 3) / 10, 0, 1);
// pitch glide
const g = Math.max(0.002, this.scoreF0 !== null ? 0.03 : this.source.glide);
this.f0 *= Math.pow(f0Target / this.f0, 1 - Math.exp(-dt / g));
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index e51ac9d..b3224a2 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -18,6 +18,8 @@ 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 { SingPanel } from "./components/SingPanel.tsx";
+import { playDemo, DEMO_SONGS } from "./singing.ts";
import type { Mode } from "./store.ts";
import type { BodyName } from "../worklet/protocol.ts";
@@ -49,6 +51,7 @@ function TopBar() {
options={[
{ value: "play", label: "Play" },
{ value: "speak", label: "Speak" },
+ { value: "sing", label: "Sing" },
{ value: "bestiary", label: "Bestiary" },
{ value: "beatbox", label: "Beatbox" },
]}
@@ -113,7 +116,8 @@ function StartPrompt() {
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."],
speak: ["Every sound here is produced by simulating air moving through a throat, mouth and nose.", "Start the voice", "Then type something and press Speak, or tap a sound in the chart."],
- }[mode as "bestiary" | "beatbox" | "speak"] ?? ["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."];
+ sing: ["Every sound here is produced by simulating air moving through a throat, mouth and nose.", "Start and hear a song", "Then play the keys: each note sings the next syllable of the lyrics."],
+ }[mode as "bestiary" | "beatbox" | "speak" | "sing"] ?? ["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>{copy[0]}</p>
@@ -125,6 +129,7 @@ function StartPrompt() {
const first = creatureById(creature)?.calls[0];
if (mode === "bestiary" && first) playCall(first.id);
else if (mode === "beatbox") setBeatPlaying(true);
+ else if (mode === "sing") void playDemo(DEMO_SONGS[0].name, useStore.getState().body);
else if (mode === "play") setHold(true);
}}
>
@@ -138,6 +143,7 @@ function StartPrompt() {
function Deck() {
const mode = useStore((s) => s.mode);
if (mode === "speak") return <SpeakPanel />;
+ if (mode === "sing") return <SingPanel />;
if (mode === "bestiary") return <BestiaryPanel />;
if (mode === "beatbox") return <BeatboxPanel />;
return (
diff --git a/src/ui/components/Keys.tsx b/src/ui/components/Keys.tsx
index d391830..7f7ddec 100644
--- a/src/ui/components/Keys.tsx
+++ b/src/ui/components/Keys.tsx
@@ -1,5 +1,6 @@
import { useEffect, useRef } from "react";
import { useStore } from "../store.ts";
+import { midiSupported } from "../midi.ts";
/** Computer-keyboard layout: two rows like a piano (A W S E D F T G Y H U J K O L P ;). */
const KEYMAP: Record<string, number> = { a: 0, w: 1, s: 2, e: 3, d: 4, f: 5, t: 6, g: 7, y: 8, h: 9, u: 10, j: 11, k: 12, o: 13, l: 14, p: 15, ";": 16 };
@@ -61,21 +62,48 @@ export function Keys() {
};
const release = (m: number) => () => noteOff(m);
return (
- <div className="keys" aria-label="Keyboard. Computer keys A to semicolon play notes; Z and X change octave.">
- <div className="white-row">
- {whites.map((m) => (
- <button key={m} className={`key white${held.includes(m) ? " down" : ""}`} onPointerDown={press(m)} onPointerUp={release(m)} onPointerCancel={release(m)} aria-label={`Note ${m}`} />
- ))}
- </div>
- <div className="black-row">
- {whites.map((m, i) => {
- const b = m + 1;
- const hasBlack = isBlack(b) && i < whites.length - 1;
- return hasBlack ? (
- <button key={b} className={`key black${held.includes(b) ? " down" : ""}`} style={{ left: `calc(${((i + 1) / whites.length) * 100}% - 1.1%)` }} onPointerDown={press(b)} onPointerUp={release(b)} onPointerCancel={release(b)} aria-label={`Note ${b}`} />
- ) : null;
- })}
+ <div className="keys-row">
+ <MidiButton />
+ <div className="keys" aria-label="Keyboard. Computer keys A to semicolon play notes; Z and X change octave.">
+ <div className="white-row">
+ {whites.map((m) => (
+ <button key={m} className={`key white${held.includes(m) ? " down" : ""}`} onPointerDown={press(m)} onPointerUp={release(m)} onPointerCancel={release(m)} aria-label={`Note ${m}`} />
+ ))}
+ </div>
+ <div className="black-row">
+ {whites.map((m, i) => {
+ const b = m + 1;
+ const hasBlack = isBlack(b) && i < whites.length - 1;
+ return hasBlack ? (
+ <button key={b} className={`key black${held.includes(b) ? " down" : ""}`} style={{ left: `calc(${((i + 1) / whites.length) * 100}% - 1.1%)` }} onPointerDown={press(b)} onPointerUp={release(b)} onPointerCancel={release(b)} aria-label={`Note ${b}`} />
+ ) : null;
+ })}
+ </div>
</div>
</div>
);
}
+
+/** Connect a MIDI keyboard (any mode with keys); shows what is connected. */
+function MidiButton() {
+ const midi = useStore((s) => s.midi);
+ const setMidi = useStore((s) => s.setMidi);
+ if (!midiSupported()) return null;
+ const on = midi.status === "on";
+ const status =
+ midi.status === "connecting"
+ ? "Connecting…"
+ : midi.status === "denied"
+ ? "Blocked by the browser"
+ : on
+ ? midi.inputs.length
+ ? midi.inputs.join(", ")
+ : "Plug one in"
+ : "Off";
+ return (
+ <button className={`midi${on ? " on" : ""}`} aria-pressed={on} onClick={() => setMidi(!on)} title={on ? "Disconnect the MIDI keyboard" : "Play with a MIDI keyboard (the browser asks for access)"}>
+ <span className="midi-name">MIDI keyboard</span>
+ <span className="midi-status">{status}</span>
+ </button>
+ );
+}
diff --git a/src/ui/components/PianoRoll.tsx b/src/ui/components/PianoRoll.tsx
new file mode 100644
index 0000000..51cae2c
--- /dev/null
+++ b/src/ui/components/PianoRoll.tsx
@@ -0,0 +1,115 @@
+import { useRef } from "react";
+import { useCanvasLoop, font } from "../useCanvas.ts";
+import { engine } from "../../audio/AudioEngine.ts";
+import { useStore } from "../store.ts";
+import { roll, tickSinging } from "../singing.ts";
+import { C } from "../colors.ts";
+
+/** pixels per second of voice time */
+const SPEED = 96;
+/** the "now" line, as a fraction of the width: the rest shows what is coming */
+const NOW_AT = 0.7;
+/** semitones shown */
+const SPAN = 25;
+const BLACK = [1, 3, 6, 8, 10];
+const NAMES = ["C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B"];
+const KEY_CENTRE: Record<string, number> = { male: 54, female: 66, child: 70 };
+
+const hzToMidi = (f: number) => 69 + 12 * Math.log2(f / 440);
+
+/**
+ * Scrolling piano roll for Sing mode: the notes asked for (bars, with their syllables) and the
+ * pitch the vocal folds actually produced (a trace that shows the onsets, glides and vibrato).
+ */
+export function PianoRoll() {
+ const st = useRef({ centre: NaN, trace: [] as { t: number; m: number; v: number }[], lastClock: -1 });
+ const ref = useCanvasLoop(({ ctx, w, h, dt }) => {
+ tickSinging();
+ const s = st.current;
+ const body = useStore.getState().body;
+ const tele = engine.latest?.t;
+ const clock = engine.voiceClock() ?? 0;
+ // sung pitch, sampled as telemetry arrives
+ if (tele && tele.clock !== s.lastClock) {
+ s.lastClock = tele.clock;
+ s.trace.push({ t: tele.clock, m: tele.f0 > 20 ? hzToMidi(tele.f0) : NaN, v: tele.voicing });
+ const cut = tele.clock - (w * NOW_AT) / SPEED - 1;
+ while (s.trace.length && s.trace[0].t < cut) s.trace.shift();
+ }
+ const tLeft = clock - (w * NOW_AT) / SPEED, tRight = clock + (w * (1 - NOW_AT)) / SPEED;
+ const x = (t: number) => (t - tLeft) * SPEED;
+ // follow the notes on screen (slowly), else rest on the keyboard's middle
+ let lo = Infinity, hi = -Infinity;
+ for (const n of roll.notes) {
+ if ((n.t1 ?? clock) < tLeft || n.t0 > tRight) continue;
+ lo = Math.min(lo, n.midi);
+ hi = Math.max(hi, n.midi);
+ }
+ const want = lo <= hi ? (lo + hi) / 2 : KEY_CENTRE[body] ?? 60;
+ if (!Number.isFinite(s.centre)) s.centre = want;
+ s.centre += (want - s.centre) * (1 - Math.exp(-dt / 0.6));
+ const bottom = s.centre - SPAN / 2;
+ const rowH = h / SPAN;
+ const y = (m: number) => h - (m - bottom + 0.5) * rowH;
+
+ ctx.fillStyle = C.black;
+ ctx.fillRect(0, 0, w, h);
+ // keyboard rows: black-key rows a shade lighter, a line and a name at each C
+ ctx.font = font(10.5, 500);
+ ctx.textBaseline = "middle";
+ for (let m = Math.floor(bottom) - 1; m <= Math.ceil(bottom + SPAN) + 1; m++) {
+ const pc = ((m % 12) + 12) % 12;
+ const yc = y(m);
+ if (BLACK.includes(pc)) {
+ ctx.fillStyle = "#0b0d0e";
+ ctx.fillRect(0, yc - rowH / 2, w, rowH);
+ }
+ if (pc === 0) {
+ ctx.fillStyle = C.line;
+ ctx.fillRect(0, Math.round(yc + rowH / 2) - 0.5, w, 1);
+ ctx.fillStyle = C.textDim;
+ ctx.fillText(`${NAMES[pc]}${Math.floor(m / 12) - 1}`, 6, yc);
+ }
+ }
+ // notes
+ const barH = Math.max(3, rowH - 2);
+ ctx.textBaseline = "alphabetic";
+ ctx.font = font(12, 550);
+ for (const n of roll.notes) {
+ const t1 = n.t1 ?? clock;
+ if (t1 < tLeft || n.t0 > tRight) continue;
+ const x0 = x(n.t0), x1 = Math.max(x0 + 3, x(t1));
+ const yc = y(n.midi);
+ const live = n.t0 <= clock && clock <= t1;
+ ctx.fillStyle = live ? C.caliper : n.t0 > clock ? "rgba(242, 207, 91, 0.32)" : "rgba(242, 207, 91, 0.58)";
+ ctx.beginPath();
+ ctx.roundRect(x0, yc - barH / 2, x1 - x0, barH, Math.min(3, barH / 2));
+ ctx.fill();
+ if (n.text && n.text !== "~") {
+ ctx.fillStyle = live ? C.text : C.textDim;
+ ctx.fillText(n.text, x0 + 1, yc - barH / 2 - 4);
+ }
+ }
+ // the pitch actually sung
+ ctx.strokeStyle = "rgb(240, 88, 28)";
+ ctx.lineWidth = 1.6;
+ ctx.lineJoin = "round";
+ ctx.beginPath();
+ let pen = false;
+ for (const p of s.trace) {
+ if (!(p.v > 0.3) || !Number.isFinite(p.m) || p.t < tLeft) {
+ pen = false;
+ continue;
+ }
+ const px = x(p.t), py = y(p.m);
+ if (pen) ctx.lineTo(px, py);
+ else ctx.moveTo(px, py);
+ pen = true;
+ }
+ ctx.stroke();
+ // now
+ ctx.fillStyle = C.caliperDim;
+ ctx.fillRect(Math.round(w * NOW_AT) - 0.5, 0, 1, h);
+ });
+ return <canvas ref={ref} className="instrument-canvas roll-canvas" aria-label="Piano roll: the notes played, their syllables, and the pitch actually sung" />;
+}
diff --git a/src/ui/components/SingPanel.tsx b/src/ui/components/SingPanel.tsx
new file mode 100644
index 0000000..f01bc4b
--- /dev/null
+++ b/src/ui/components/SingPanel.tsx
@@ -0,0 +1,120 @@
+import { useStore } from "../store.ts";
+import { useSing, playDemo, stopSinging, DEMO_SONGS } from "../singing.ts";
+import { Slider, Toggle } from "./Controls.tsx";
+import { Keys } from "./Keys.tsx";
+import { PianoRoll } from "./PianoRoll.tsx";
+
+/** epilarynx narrowing for the singer's ring (measured: +3 to +12 dB at 2.4–3.6 kHz, adult male) */
+const RING = 0.85;
+
+function Lyrics() {
+ const lyrics = useSing((s) => s.lyrics);
+ const syllables = useSing((s) => s.syllables);
+ const cursor = useSing((s) => s.cursor);
+ const demo = useSing((s) => s.demo);
+ const demoAt = useSing((s) => s.demoAt);
+ const setLyrics = useSing((s) => s.setLyrics);
+ const setCursor = useSing((s) => s.setCursor);
+ const at = demo ? demoAt : -1;
+ return (
+ <div className="panel lyrics-panel">
+ <h2>Lyrics</h2>
+ <textarea
+ value={lyrics}
+ onChange={(e) => setLyrics(e.target.value)}
+ onKeyDown={(e) => e.stopPropagation()}
+ rows={2}
+ aria-label="Lyrics to sing"
+ placeholder="Type the words to sing"
+ />
+ <div className="syllables" role="group" aria-label="Syllables. Each note sings the marked one; choose another to start there.">
+ {syllables.map((s, i) => (
+ <span key={i} className={`syl-wrap${s.wordEnd ? " word-end" : ""}`}>
+ <button
+ className={`syl${!demo && i === cursor ? " next" : ""}${i === at ? " now" : ""}${s.melisma ? " held" : ""}`}
+ onClick={() => setCursor(i)}
+ aria-current={!demo && i === cursor ? "step" : undefined}
+ title={s.melisma ? "Held vowel: carries the previous syllable onto this note" : `Sing from “${s.text}”`}
+ >
+ {s.text}
+ </button>
+ {s.phraseEnd && (
+ <span className="breath-mark" aria-label="breath">
+ ’
+ </span>
+ )}
+ </span>
+ ))}
+ {!syllables.length && <span className="dim">No words: the keys sing “ah”.</span>}
+ </div>
+ <div className="row">
+ <button className="ghost" onClick={() => setCursor(0)} disabled={cursor === 0 && !demo}>
+ Back to the first syllable
+ </button>
+ </div>
+ <p className="dim">
+ Each note sings the next syllable. Hold a key while you press the next one to sing legato. A lone “-” between words holds a vowel over several notes; hyphens split a word your way (“ti-ger”).
+ </p>
+ </div>
+ );
+}
+
+function SongAndVoice() {
+ const body = useStore((s) => s.body);
+ const start = useStore((s) => s.start);
+ const source = useStore((s) => s.source);
+ const setSource = useStore((s) => s.setSource);
+ const epilarynx = useStore((s) => s.artic.epilarynx);
+ const setArtic = useStore((s) => s.setArtic);
+ const demo = useSing((s) => s.demo);
+ const vibrato = useSing((s) => s.vibrato);
+ const setVibrato = useSing((s) => s.setVibrato);
+ return (
+ <div className="panel song-panel">
+ <h2>Songs</h2>
+ <div className="examples" role="group" aria-label="Demo songs">
+ {DEMO_SONGS.map((s) => (
+ <button
+ key={s.name}
+ className={`chip${demo === s.name ? " on" : ""}`}
+ aria-pressed={demo === s.name}
+ onClick={async () => {
+ if (demo === s.name) {
+ stopSinging();
+ return;
+ }
+ await start();
+ await playDemo(s.name, body);
+ }}
+ >
+ {demo === s.name ? `Stop “${s.name}”` : s.name}
+ </button>
+ ))}
+ </div>
+ <h2>Voice</h2>
+ <Slider label="Vibrato depth" value={vibrato} min={0} max={80} onChange={(v) => setVibrato(Math.round(v))} format={(v) => `${Math.round(v)} cents`} />
+ <Slider label="Vibrato rate" value={source.vibratoRate} min={3.5} max={7.5} onChange={(v) => setSource({ vibratoRate: v })} format={(v) => `${v.toFixed(1)} Hz`} />
+ <Slider label="Breathiness" value={source.breathiness} min={0} max={1} onChange={(v) => setSource({ breathiness: v })} format={(v) => `${Math.round(v * 100)} %`} />
+ <Toggle label="Singer’s ring" checked={epilarynx >= RING - 0.05} onChange={(on) => setArtic({ epilarynx: on ? RING : 0 })} />
+ <p className="dim">Narrows the tube just above the vocal folds, adding the bright ring near 3 kHz that lets an opera voice carry.</p>
+ </div>
+ );
+}
+
+export function SingPanel() {
+ return (
+ <>
+ <section className="sing">
+ <Lyrics />
+ <SongAndVoice />
+ <figure className="instrument roll-panel">
+ <figcaption>Notes, and the pitch actually sung</figcaption>
+ <PianoRoll />
+ </figure>
+ </section>
+ <footer className="keys-bar">
+ <Keys />
+ </footer>
+ </>
+ );
+}
diff --git a/src/ui/midi.ts b/src/ui/midi.ts
new file mode 100644
index 0000000..2294c6e
--- /dev/null
+++ b/src/ui/midi.ts
@@ -0,0 +1,63 @@
+/**
+ * Web MIDI keyboards: note on/off (with velocity) from every connected input, including ones
+ * plugged in later. All-notes-off and unplugging release whatever that input was holding.
+ */
+export type MidiStatus = "off" | "connecting" | "on" | "unsupported" | "denied";
+
+export interface MidiHandlers {
+ noteOn: (note: number, velocity: number) => void;
+ noteOff: (note: number) => void;
+ /** names of the connected inputs (on every change) */
+ inputs: (names: string[]) => void;
+}
+
+export const midiSupported = (): boolean => typeof navigator !== "undefined" && typeof navigator.requestMIDIAccess === "function";
+
+let access: MIDIAccess | null = null;
+/** notes held per input id */
+const held = new Map<string, Set<number>>();
+
+export async function connectMidi(h: MidiHandlers): Promise<void> {
+ if (access) return;
+ const a = await navigator.requestMIDIAccess({ sysex: false });
+ access = a;
+ const releaseInput = (id: string) => {
+ const notes = held.get(id);
+ if (notes) for (const n of notes) h.noteOff(n);
+ held.delete(id);
+ };
+ const attach = () => {
+ const names: string[] = [];
+ const live = new Set<string>();
+ a.inputs.forEach((input) => {
+ live.add(input.id);
+ names.push(input.name || "MIDI keyboard");
+ input.onmidimessage = (e: MIDIMessageEvent) => {
+ const d = e.data;
+ if (!d || d.length < 2) return;
+ const kind = d[0] & 0xf0;
+ const notes = held.get(input.id) ?? new Set<number>();
+ held.set(input.id, notes);
+ if (kind === 0x90 && d[2] > 0) {
+ notes.add(d[1]);
+ h.noteOn(d[1], d[2]);
+ } else if (kind === 0x80 || (kind === 0x90 && d[2] === 0)) {
+ if (notes.delete(d[1])) h.noteOff(d[1]);
+ } else if (kind === 0xb0 && (d[1] === 123 || d[1] === 120)) releaseInput(input.id); // all notes / sound off
+ };
+ });
+ for (const id of [...held.keys()]) if (!live.has(id)) releaseInput(id);
+ h.inputs(names);
+ };
+ a.onstatechange = attach;
+ attach();
+}
+
+export function disconnectMidi(h: Pick<MidiHandlers, "noteOff">): void {
+ if (!access) return;
+ access.inputs.forEach((input) => (input.onmidimessage = null));
+ access.onstatechange = null;
+ access = null;
+ for (const notes of held.values()) for (const n of notes) h.noteOff(n);
+ held.clear();
+}
diff --git a/src/ui/singing.ts b/src/ui/singing.ts
new file mode 100644
index 0000000..92bce1a
--- /dev/null
+++ b/src/ui/singing.ts
@@ -0,0 +1,265 @@
+/**
+ * Sing mode on the main thread. The lyrics become syllables with a cursor; each key sings the
+ * next syllable at its pitch. A key pressed while the previous one is still down sings legato
+ * (the previous syllable's coda runs straight into the next onset); a "-" in the lyrics holds
+ * the vowel onto a new pitch (melisma). Releasing the sounding key while another is still down
+ * glides back to that key on the same vowel. Key velocity sets the breath.
+ * Demo songs are planned whole (planSong) and sent as one score.
+ */
+import { create } from "zustand";
+import { engine } from "../audio/AudioEngine.ts";
+import { g2p } from "./speech.ts";
+import { lyricsToSyllables, type Syllable } from "../engine/phonetics/syllables.ts";
+import { planSong, planNoteOn, planNoteOff, planMelisma } from "../engine/phonetics/sing.ts";
+import { DEMO_SONGS } from "../engine/phonetics/songs.ts";
+import type { Gesture } from "../engine/control/score.ts";
+import type { BodyName } from "../worklet/protocol.ts";
+
+/** A note on the piano roll, on the voice clock (s); t1 is null while it is held. */
+export interface RollNote {
+ midi: number;
+ t0: number;
+ t1: number | null;
+ text: string;
+ demo: boolean;
+}
+
+/** What the piano roll draws, read every frame (mutated in place: no re-render per note). */
+export const roll: { notes: RollNote[] } = { notes: [] };
+
+export const DEFAULT_LYRICS = "Hello there, I am a voice made of air.";
+
+/** sung when the lyrics are empty */
+const AH: Syllable = { text: "ah", onset: [], nucleus: { ipa: "ɑ", stress: 1 }, coda: [], wordEnd: true, phraseEnd: false };
+
+interface SingState {
+ lyrics: string;
+ syllables: Syllable[];
+ /** the syllable the next key sings */
+ cursor: number;
+ /** vibrato depth on held vowels (cents) */
+ vibrato: number;
+ /** the demo song playing, if any */
+ demo: string | null;
+ /** index of the demo syllable being sung (−1: none yet) */
+ demoAt: number;
+ setLyrics: (text: string) => void;
+ setCursor: (i: number) => void;
+ setVibrato: (cents: number) => void;
+}
+
+export const useSing = create<SingState>((set, get) => ({
+ lyrics: DEFAULT_LYRICS,
+ syllables: lyricsToSyllables(DEFAULT_LYRICS, g2p),
+ cursor: 0,
+ vibrato: 35,
+ demo: null,
+ demoAt: -1,
+ setLyrics: (text) => {
+ stopDemo();
+ set({ lyrics: text, syllables: lyricsToSyllables(text, g2p), cursor: 0 });
+ },
+ setCursor: (i) => set({ cursor: Math.max(0, Math.min(i, Math.max(0, get().syllables.length - 1))) }),
+ setVibrato: (cents) => set({ vibrato: cents }),
+}));
+
+/** Load the pronouncing dictionary, then re-read the lyrics with it (the cursor stays). */
+export function ensureDictionary(): void {
+ if (g2p.loaded) return;
+ g2p
+ .load()
+ .then(() => {
+ const s = useSing.getState();
+ const syllables = lyricsToSyllables(s.lyrics, g2p);
+ useSing.setState({ syllables, cursor: Math.min(s.cursor, Math.max(0, syllables.length - 1)) });
+ })
+ .catch(() => {
+ // no dictionary: the letter-to-sound rules keep working
+ });
+}
+
+// ---- live notes
+
+interface Sounding {
+ midi: number;
+ /** the syllable whose vowel is sounding (a melisma keeps its parent's, for the coda) */
+ syl: Syllable;
+ tag: number;
+ note: RollNote;
+}
+
+let sounding: Sounding | null = null;
+/** keys down, oldest first */
+let keys: number[] = [];
+/** gesture tags: a note uses tag (articulation, breath) and tag + 1 (pitch, vibrato) */
+let nextTag = 2;
+
+/** breath level for a key velocity (1 at the on-screen keys' default of 96) */
+const breathFor = (velocity: number) => 0.62 + 0.4 * Math.min(1, Math.max(0, velocity / 96)) + 0.12 * Math.max(0, (velocity - 96) / 31);
+
+const now = () => engine.voiceClock() ?? 0;
+
+function addNote(midi: number, t0: number, text: string, demo = false, t1: number | null = null): RollNote {
+ const n: RollNote = { midi, t0, t1, text, demo };
+ roll.notes.push(n);
+ // keep a minute of history
+ const cut = t0 - 60;
+ if (roll.notes.length > 400 || (roll.notes[0] && (roll.notes[0].t1 ?? t0) < cut)) roll.notes = roll.notes.filter((x) => (x.t1 ?? t0) >= cut).slice(-400);
+ return n;
+}
+
+/** The syllable a melisma at index i continues. */
+function parentOf(syls: Syllable[], i: number): Syllable {
+ for (let k = i; k >= 0; k--) if (!syls[k].melisma) return syls[k];
+ return AH;
+}
+
+function startNote(syl: Syllable, midi: number, velocity: number, body: BodyName, text: string): void {
+ const t = now();
+ const tag = nextTag;
+ nextTag += 2;
+ const from = sounding;
+ if (from) {
+ engine.release(from.tag);
+ engine.release(from.tag + 1);
+ from.note.t1 = t;
+ }
+ const gs: Gesture[] = planNoteOn(syl, midi, { body, vibrato: useSing.getState().vibrato, tag, legatoFrom: from ? { syl: from.syl, midi: from.midi } : undefined });
+ const breath = breathFor(velocity);
+ for (const g of gs) if (g.targets.breath !== undefined) g.targets = { ...g.targets, breath: g.targets.breath * breath };
+ engine.scheduleGestures(gs);
+ sounding = { midi, syl, tag, note: addNote(midi, t, text) };
+}
+
+/** The held vowel moves to a new pitch (melisma, or back to a key still down). */
+function glide(midi: number, text: string): void {
+ const s = sounding!;
+ const t = now();
+ engine.release(s.tag + 1);
+ engine.scheduleGestures(planMelisma(midi, { vibrato: useSing.getState().vibrato, tag: s.tag }));
+ s.note.t1 = t;
+ s.midi = midi;
+ s.note = addNote(midi, t, text);
+}
+
+export function singNoteOn(midi: number, velocity: number, body: BodyName): void {
+ stopDemo();
+ keys = keys.filter((k) => k !== midi).concat(midi);
+ const st = useSing.getState();
+ const syls = st.syllables.length ? st.syllables : [AH];
+ const i = st.cursor % syls.length;
+ const syl = syls[i];
+ if (syl.melisma && sounding) glide(midi, syl.text);
+ // a melisma with nothing held: sing its vowel again, without the onset
+ else startNote(syl.melisma ? { ...parentOf(syls, i), onset: [] } : syl, midi, velocity, body, syl.text);
+ useSing.setState({ cursor: (i + 1) % syls.length });
+}
+
+export function singNoteOff(midi: number, body: BodyName): void {
+ keys = keys.filter((k) => k !== midi);
+ const s = sounding;
+ if (!s || s.midi !== midi) return;
+ if (keys.length) {
+ glide(keys[keys.length - 1], "~");
+ return;
+ }
+ engine.release(s.tag);
+ engine.release(s.tag + 1);
+ s.note.t1 = now();
+ sounding = null;
+ // a melisma comes next: this vowel carries on there, and the coda waits for the chain's end
+ const st = useSing.getState();
+ if (st.syllables[st.cursor]?.melisma) return;
+ const tail = planNoteOff(s.syl, midi, body);
+ if (tail.length) engine.scheduleGestures(tail);
+}
+
+// ---- demo songs
+
+interface DemoRun {
+ id: number;
+ /** note start/end times in plan time (s) */
+ times: [number, number][];
+ midi: number[];
+ text: string[];
+ end: number;
+ /** voice clock of plan time 0, once the worklet has it */
+ offset: number | null;
+}
+
+let demoRun: DemoRun | null = null;
+
+engine.onPlanned((m) => {
+ const d = demoRun;
+ if (!d || m.id !== d.id) return;
+ d.offset = m.t0;
+ d.times.forEach(([a, b], k) => addNote(d.midi[k], m.t0 + a, d.text[k], true, m.t0 + b - 0.02));
+});
+
+export async function playDemo(name: string, body: BodyName): Promise<void> {
+ const song = DEMO_SONGS.find((s) => s.name === name);
+ if (!song) return;
+ stopSinging();
+ try {
+ await g2p.load();
+ } catch {
+ // letter-to-sound rules
+ }
+ const syl = lyricsToSyllables(song.lyrics, g2p);
+ if (!syl.length) return;
+ const shift = song.octave[body] * 12;
+ const notes = song.notes.map((n, i) => ({ midi: n[0] + shift, beats: n[1], syl: syl[i % syl.length] }));
+ const t0 = 0.35;
+ const plan = planSong(notes, { body, bpm: song.bpm, t0, vibrato: useSing.getState().vibrato });
+ const beat = 60 / song.bpm;
+ let t = t0;
+ const times = notes.map((n): [number, number] => {
+ const a = t;
+ t += n.beats * beat;
+ return [a, t];
+ });
+ const id = engine.schedule({ gestures: plan.gestures, segments: plan.segments, end: plan.end });
+ demoRun = { id, times, midi: notes.map((n) => n.midi), text: notes.map((n) => n.syl.text), end: plan.end, offset: null };
+ useSing.setState({ lyrics: song.lyrics, syllables: syl, cursor: 0, demo: song.name, demoAt: -1 });
+}
+
+function stopDemo(): void {
+ const d = demoRun;
+ if (!d) return;
+ demoRun = null;
+ engine.stopSpeech();
+ // notes not yet sung leave the roll; the one sounding ends now
+ const t = now();
+ roll.notes = roll.notes.filter((n) => !(n.demo && n.t0 > t));
+ for (const n of roll.notes) if (n.demo && n.t1 !== null && n.t1 > t) n.t1 = t;
+ useSing.setState({ demo: null, demoAt: -1 });
+}
+
+/** Called every frame while Sing mode is shown: follow the demo's progress. */
+export function tickSinging(): void {
+ const d = demoRun;
+ if (!d || d.offset === null) return;
+ const t = now() - d.offset;
+ if (t > d.end + 0.4) {
+ demoRun = null;
+ useSing.setState({ demo: null, demoAt: -1 });
+ return;
+ }
+ let k = -1;
+ while (k + 1 < d.times.length && d.times[k + 1][0] <= t) k++;
+ if (k !== useSing.getState().demoAt) useSing.setState({ demoAt: k });
+}
+
+/** Stop everything sung (leaving Sing mode, changing body). */
+export function stopSinging(): void {
+ stopDemo();
+ if (sounding) {
+ engine.release(sounding.tag);
+ engine.release(sounding.tag + 1);
+ sounding.note.t1 = now();
+ sounding = null;
+ }
+ keys = [];
+}
+
+export { DEMO_SONGS };
diff --git a/src/ui/store.ts b/src/ui/store.ts
index 66694ba..7a8681c 100644
--- a/src/ui/store.ts
+++ b/src/ui/store.ts
@@ -6,10 +6,12 @@ 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";
+import { singNoteOn, singNoteOff, stopSinging, ensureDictionary } from "./singing.ts";
+import { connectMidi, disconnectMidi, type MidiStatus } from "./midi.ts";
export const DEFAULT_F0: Record<BodyName, number> = { male: 110, female: 205, child: 260 };
-export type Mode = "play" | "speak" | "bestiary" | "beatbox";
+export type Mode = "play" | "speak" | "sing" | "bestiary" | "beatbox";
export interface BeatState {
steps: (BeatStep | null)[];
@@ -70,8 +72,11 @@ interface State {
setArtic: (v: Partial<HumanArtic>, tipFree?: boolean) => void;
setVolume: (v: number) => void;
setHold: (h: boolean) => void;
- noteOn: (midi: number) => void;
+ /** a key went down (velocity 1..127; the on-screen keys send 96) */
+ noteOn: (midi: number, velocity?: number) => void;
noteOff: (midi: number) => void;
+ midi: { status: MidiStatus; inputs: string[] };
+ setMidi: (on: boolean) => void;
setView: (v: Partial<ViewOptions>) => void;
}
@@ -90,8 +95,8 @@ export function creatureKeyHz(midi: number, p: Pick<ParamDef, "min" | "max">): n
}
function updateGate(s: { hold: boolean; heldNotes: number[]; mode: Mode; keyCall: string | null }) {
- // keys that trigger calls leave the breath to the call
- const keysBreathe = !(s.mode === "bestiary" && s.keyCall);
+ // keys that trigger calls leave the breath to the call; sung notes breathe by themselves
+ const keysBreathe = !(s.mode === "bestiary" && s.keyCall) && s.mode !== "sing";
engine.gate(s.hold || (keysBreathe && s.heldNotes.length > 0) ? 1 : 0);
}
@@ -132,8 +137,10 @@ export const useStore = create<State>((set, get) => ({
get().setBeatPlaying(false);
engine.setMic(false);
}
- // speech breathes by itself: a held breath would drone under it and through every pause
- if (m === "speak") set({ hold: false });
+ if (prev === "sing") stopSinging();
+ // speech and song breathe by themselves: a held breath would drone under them
+ if (m === "speak" || m === "sing") set({ hold: false });
+ if (m === "sing") ensureDictionary();
if (m === "beatbox") {
// a beatboxer waits with the jaw nearly closed; the sounds bring their own breath
set({ hold: false });
@@ -243,6 +250,8 @@ export const useStore = create<State>((set, get) => ({
return startPromise;
},
setBody: (b) => {
+ // the new voice starts without the old one's score: a sung note would hang
+ if (get().mode === "sing") stopSinging();
const f0 = DEFAULT_F0[b];
set((s) => ({ body: b, source: { ...s.source, f0 } }));
engine.setBody(b);
@@ -263,11 +272,12 @@ export const useStore = create<State>((set, get) => ({
set({ hold: h });
updateGate(get());
},
- noteOn: (midi) => {
+ noteOn: (midi, velocity = 96) => {
const held = get().heldNotes.filter((n) => n !== midi).concat(midi);
set({ heldNotes: held });
const s = get();
- if (s.mode === "bestiary") {
+ if (s.mode === "sing") singNoteOn(midi, velocity, s.body);
+ else if (s.mode === "bestiary") {
const pp = creatureById(s.creature)?.params.find((p) => p.role === "pitch");
const f = pp ? creatureKeyHz(midi, pp) : undefined;
if (s.keyCall) s.playCall(s.keyCall, f);
@@ -284,6 +294,10 @@ export const useStore = create<State>((set, get) => ({
const held = get().heldNotes.filter((n) => n !== midi);
set({ heldNotes: held });
const s = get();
+ if (s.mode === "sing") {
+ singNoteOff(midi, s.body);
+ return;
+ }
if (s.mode === "beatbox" && !held.length) s.setArtic({ lipAp: beatReady(s.body).lipAp, velum: NEUTRAL.velum });
if (held.length) {
// fall back to the most recent note still held (legato)
@@ -297,4 +311,24 @@ export const useStore = create<State>((set, get) => ({
updateGate(get());
},
setView: (v) => set((s) => ({ view: { ...s.view, ...v } })),
+ midi: { status: "off", inputs: [] },
+ setMidi: (on) => {
+ const noteOff = (n: number) => get().noteOff(n);
+ if (!on) {
+ disconnectMidi({ noteOff });
+ set({ midi: { status: "off", inputs: [] } });
+ return;
+ }
+ set({ midi: { status: "connecting", inputs: [] } });
+ // the click that connects is also the gesture that may start audio
+ void get().start();
+ connectMidi({
+ noteOn: (n, v) => {
+ void get().start();
+ get().noteOn(n, v);
+ },
+ noteOff,
+ inputs: (names) => set({ midi: { status: "on", inputs: names } }),
+ }).catch(() => set({ midi: { status: "denied", inputs: [] } }));
+ },
}));
diff --git a/src/ui/styles.css b/src/ui/styles.css
index 5dd5320..74a69f1 100644
--- a/src/ui/styles.css
+++ b/src/ui/styles.css
@@ -727,6 +727,147 @@ button.ghost {
row-gap: 4px;
}
+/* ---------- sing */
+.sing {
+ display: grid;
+ grid-template-columns: minmax(320px, 1.6fr) minmax(260px, 1fr);
+ gap: 10px;
+}
+
+.lyrics-panel,
+.song-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.lyrics-panel textarea {
+ width: 100%;
+ resize: vertical;
+ min-height: 52px;
+ background: var(--black);
+ color: var(--text);
+ border: 1px solid var(--line);
+ border-radius: var(--radius-s);
+ padding: 8px 10px;
+ font: inherit;
+ font-size: 16px;
+ line-height: 1.4;
+}
+
+.song-panel h2 + .examples {
+ margin-bottom: 6px;
+}
+
+.syllables {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ row-gap: 6px;
+ min-height: 34px;
+}
+
+.syl-wrap {
+ display: inline-flex;
+ align-items: center;
+ margin-right: 2px;
+}
+
+.syl-wrap.word-end {
+ margin-right: 10px;
+}
+
+.syl {
+ border: 1px solid var(--line);
+ border-radius: var(--radius-s);
+ background: var(--black);
+ padding: 2px 7px 3px;
+ font-size: 15px;
+ color: var(--text);
+ cursor: pointer;
+}
+
+.syl.held {
+ color: var(--text-dim);
+}
+
+.syl.next {
+ border-color: var(--caliper);
+ color: var(--caliper);
+ box-shadow: 0 0 0 1px var(--caliper-dim);
+}
+
+.syl.now {
+ background: var(--caliper);
+ border-color: var(--caliper);
+ color: var(--black);
+}
+
+.breath-mark {
+ margin-left: 4px;
+ color: var(--caliper);
+ font-size: 20px;
+ line-height: 1;
+}
+
+.roll-panel {
+ grid-column: 1 / -1;
+ min-height: 0;
+}
+
+.roll-canvas {
+ height: 168px;
+ border-radius: var(--radius-s);
+}
+
+.keys-row {
+ display: flex;
+ gap: 8px;
+}
+
+.keys-row .keys {
+ flex: 1;
+ min-width: 0;
+}
+
+button.midi {
+ flex: 0 0 96px;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ gap: 2px;
+ padding: 6px 8px;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-s);
+ background: transparent;
+ text-align: left;
+ cursor: pointer;
+ overflow: hidden;
+}
+
+.midi-name {
+ font-size: 12.5px;
+ font-weight: 550;
+ font-stretch: 87%;
+ line-height: 1.15;
+}
+
+.midi-status {
+ font-size: 12px;
+ font-stretch: 87%;
+ color: var(--text-dim);
+ line-height: 1.2;
+ overflow-wrap: anywhere;
+}
+
+button.midi.on {
+ border-color: var(--caliper-dim);
+}
+
+button.midi.on .midi-status {
+ color: var(--caliper);
+}
+
/* ---------- beatbox */
.beatbox {
display: grid;
@@ -1046,7 +1187,8 @@ button.ghost {
}
@media (max-width: 900px) {
- .speak {
+ .speak,
+ .sing {
grid-template-columns: 1fr;
}
}
@@ -1067,10 +1209,17 @@ button.ghost {
}
.deck,
.speak,
+ .sing,
.bestiary,
.beatbox {
order: 2;
}
+ .sing {
+ grid-template-columns: 1fr;
+ }
+ .roll-canvas {
+ height: 140px;
+ }
.seq-row {
grid-template-columns: 34px repeat(var(--steps), minmax(12px, 1fr));
gap: 2px;
@@ -1145,6 +1294,18 @@ button.ghost {
.keys {
height: 64px;
}
+ .keys-row {
+ flex-direction: column;
+ gap: 6px;
+ }
+ button.midi {
+ flex: none;
+ flex-direction: row;
+ align-items: baseline;
+ justify-content: flex-start;
+ gap: 8px;
+ padding: 4px 8px;
+ }
}
@media (prefers-reduced-motion: reduce) {
diff --git a/tests/singing-live.test.ts b/tests/singing-live.test.ts
new file mode 100644
index 0000000..2240f34
--- /dev/null
+++ b/tests/singing-live.test.ts
@@ -0,0 +1,121 @@
+/**
+ * Sing mode's live path end to end, without a browser: the key handling in src/ui/singing.ts
+ * talks to a stand-in for the audio engine that does what the worklet does with each message
+ * (schedule at clock + lead, release by tag, cancel), on a real offline voice.
+ */
+import { describe, expect, mock, test } from "bun:test";
+import { HumanVoice } from "../src/engine/voice/humanVoice.ts";
+import { midiToHz } from "../src/engine/phonetics/sing.ts";
+import type { Gesture } from "../src/engine/control/score.ts";
+
+const FS = 48000;
+let voice = new HumanVoice({ fsOut: FS });
+const fakeEngine = {
+ latest: null,
+ voiceClock: () => voice.clock,
+ onPlanned: () => () => {},
+ scheduleGestures: (gs: Gesture[], lead = 0.006) => {
+ const off = voice.clock + lead;
+ voice.schedule(gs.map((g) => ({ ...g, t0: g.t0 + off, t1: g.t1 + off })));
+ },
+ schedule: (plan: { gestures: Gesture[] }) => {
+ voice.cancelScore();
+ const off = voice.clock + 0.03;
+ voice.schedule(plan.gestures.map((g) => ({ ...g, t0: g.t0 + off, t1: g.t1 + off })));
+ return 1;
+ },
+ release: (tag: number) => voice.release(tag),
+ stopSpeech: () => voice.cancelScore(),
+};
+mock.module("../src/audio/AudioEngine.ts", () => ({ engine: fakeEngine }));
+const { useSing, singNoteOn, singNoteOff } = await import("../src/ui/singing.ts");
+
+/** Render `sec` seconds; per 2.7 ms block: f0, voicing, output RMS, narrowest oral area. */
+function run(sec: number) {
+ const n = Math.round(sec * FS);
+ const out = new Float32Array(n);
+ const f0: number[] = [], voicing: number[] = [], rms: number[] = [], minOral: number[] = [];
+ for (let i = 0; i < n; i += 128) {
+ const m = Math.min(128, n - i);
+ voice.render(out, i, m);
+ let e = 0;
+ for (let j = i; j < i + m; j++) e += out[j] * out[j];
+ rms.push(Math.sqrt(e / m));
+ f0.push(voice.glottis.f0Now);
+ voicing.push(voice.glottis.voicing);
+ let mn = Infinity;
+ for (const a of voice.airway.orAreas) mn = Math.min(mn, a);
+ minOral.push(mn);
+ }
+ // the last 40 % of the span, where a note has settled
+ const late = <T,>(xs: T[]) => xs.slice(Math.floor(xs.length * 0.6));
+ return { f0, voicing, rms, minOral, late };
+}
+const median = (xs: number[]) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];
+const cents = (f: number, midi: number) => 1200 * Math.log2(f / midiToHz(midi));
+
+describe("Sing mode, live keys", () => {
+ test("each key sings the next syllable at its pitch; legato, melisma and release to silence", () => {
+ voice = new HumanVoice({ fsOut: FS });
+ useSing.getState().setVibrato(0);
+ useSing.getState().setLyrics("la ma -");
+ expect(useSing.getState().syllables.map((s) => s.text)).toEqual(["la", "ma", "~"]);
+ run(0.1);
+
+ // first key: /la/ on A2
+ singNoteOn(45, 96, "male");
+ expect(useSing.getState().cursor).toBe(1);
+ const a = run(0.5);
+ expect(Math.abs(cents(median(a.late(a.f0)), 45))).toBeLessThan(30);
+ expect(Math.min(...a.late(a.voicing))).toBeGreaterThan(0.5);
+
+ // second key pressed while the first is down: legato into /ma/ on C3 (the lips close once)
+ singNoteOn(48, 96, "male");
+ const b = run(0.5);
+ expect(Math.abs(cents(median(b.late(b.f0)), 48))).toBeLessThan(30);
+ expect(Math.min(...b.minOral)).toBeLessThan(0.05); // the /m/ closure
+ expect(Math.min(...b.late(b.minOral))).toBeGreaterThan(0.2); // open again on the vowel
+
+ // releasing the first key (no longer sounding) changes nothing
+ singNoteOff(45, "male");
+ const c = run(0.2);
+ expect(Math.min(...c.voicing)).toBeGreaterThan(0.5);
+
+ // melisma: the vowel carries on to E3 without a consonant
+ singNoteOn(52, 96, "male");
+ expect(useSing.getState().cursor).toBe(0); // wrapped round
+ const d = run(0.5);
+ expect(Math.abs(cents(median(d.late(d.f0)), 52))).toBeLessThan(30);
+ expect(Math.min(...d.minOral)).toBeGreaterThan(0.2);
+ expect(Math.min(...d.voicing)).toBeGreaterThan(0.5);
+
+ // releasing E3 while C3 is still down glides back to C3 on the same vowel
+ singNoteOff(52, "male");
+ const e = run(0.4);
+ expect(Math.abs(cents(median(e.late(e.f0)), 48))).toBeLessThan(30);
+ expect(Math.min(...e.voicing)).toBeGreaterThan(0.5);
+
+ // last key up: the note ends and the voice falls silent
+ singNoteOff(48, "male");
+ const f = run(0.6);
+ let peak = 0;
+ for (const r of [...a.rms, ...b.rms]) peak = Math.max(peak, r);
+ expect(Math.max(...f.rms.slice(Math.floor(0.3 * FS / 128)))).toBeLessThan(peak * 0.003); // < -50 dB
+ });
+
+ test("a soft key breathes less than a hard one", () => {
+ const level = (velocity: number) => {
+ voice = new HumanVoice({ fsOut: FS });
+ useSing.getState().setLyrics("ah");
+ run(0.05);
+ singNoteOn(50, velocity, "male");
+ const r = run(0.5);
+ singNoteOff(50, "male");
+ run(0.4);
+ return { p: voice.source.pressure, rms: median(r.late(r.rms)) };
+ };
+ const soft = level(30), hard = level(127);
+ if (process.env.SING_VERBOSE) console.log(`hard vs soft key: ${(20 * Math.log10(hard.rms / soft.rms)).toFixed(1)} dB`);
+ expect(hard.rms / soft.rms).toBeGreaterThan(1.6); // > 4 dB
+ });
+});
diff --git a/tools/e2e.ts b/tools/e2e.ts
index a06bd20..e81adf1 100644
--- a/tools/e2e.ts
+++ b/tools/e2e.ts
@@ -79,6 +79,42 @@ async function run(viewport: { width: number; height: number }, tag: string) {
await page.locator("button.ipa", { hasText: "ʃ" }).first().click();
await page.waitForTimeout(700);
await page.screenshot({ path: `${outDir}/${tag}-4-pad.png` });
+ // sing mode: a key sings the marked syllable and moves the cursor; legato; a demo song
+ await page.getByRole("radio", { name: "Sing" }).click();
+ await page.waitForTimeout(600);
+ const rms = () =>
+ page.evaluate(() => {
+ // @ts-expect-error debug handle
+ return window.__chimeraEngine?.latest?.t?.outRms ?? -1;
+ });
+ const nextSyl = () => page.locator(".syl.next").textContent().catch(() => null);
+ const sylBefore = await nextSyl();
+ await page.keyboard.down("d");
+ await page.waitForTimeout(450);
+ const singing = await rms();
+ await page.keyboard.down("g"); // legato into the next syllable
+ await page.waitForTimeout(350);
+ await page.keyboard.up("d");
+ await page.waitForTimeout(250);
+ await page.keyboard.up("g");
+ await page.waitForTimeout(900);
+ const after = await rms();
+ const sylAfter = await nextSyl();
+ logs.push(`[${tag}] sing: next syllable ${sylBefore} -> ${sylAfter}, rms while held ${singing.toFixed(4)}, then silence ${after.toFixed(4)}`);
+ if (!(singing > 0.01)) errors.push(`[${tag}] a sung key made no sound (${singing})`);
+ if (!(after < 1e-3)) errors.push(`[${tag}] voice still sounding after the sung notes: ${after}`);
+ if (sylBefore === sylAfter) errors.push(`[${tag}] the syllable cursor did not move (${sylBefore})`);
+ await page.getByRole("button", { name: "Made of air" }).click();
+ await page.waitForTimeout(2200);
+ const demoRms = await rms();
+ const demoNow = await page.locator(".syl.now").textContent().catch(() => null);
+ await page.screenshot({ path: `${outDir}/${tag}-5-sing.png`, fullPage: tag !== "desktop" });
+ await page.getByRole("button", { name: /^Stop “Made of air”$/ }).click();
+ await page.waitForTimeout(700);
+ const demoStopped = await rms();
+ logs.push(`[${tag}] sing demo: rms ${demoRms.toFixed(4)} on "${demoNow}", after stop ${demoStopped.toFixed(4)}`);
+ if (!(demoRms > 0.01) || !demoNow) errors.push(`[${tag}] demo song not singing (rms ${demoRms}, syllable ${demoNow})`);
+ if (!(demoStopped < 1e-3)) errors.push(`[${tag}] demo still sounding after stop: ${demoStopped}`);
// bestiary: every creature, its first call, a key in held-voice mode, and the sustain toggle
await page.getByRole("radio", { name: "Bestiary" }).click();
await page.waitForTimeout(300);
@@ -145,4 +181,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|beatbox|silence/i.test(l)).slice(0, 40).join("\n"));
+console.log(logs.filter((l) => /load|warn|transcription|creature|held|back to|beatbox|silence|sing/i.test(l)).slice(0, 40).join("\n"));