the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Singing engine (no UI yet): syllables on notes, live held notes, demo songs; clean output limiter
Jameson Hodge3116f16ee8ab
diff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.tsindex 75c9e5a..fe233fc 100644--- a/src/audio/AudioEngine.ts+++ b/src/audio/AudioEngine.ts@@ -180,6 +180,16 @@ export class AudioEngine {this.send({ type: "beat", ...m });}+ /** End the sung note (open-ended gestures) with this tag. */+ release(tag: number): void {+ this.send({ type: "release", tag });+ }++ /** Gestures planned on the main thread, times relative to arrival + lead (live playing). */+ scheduleGestures(gestures: import("../engine/control/score.ts").Gesture[], lead = 0.006): void {+ this.send({ type: "schedule", gestures, segments: [], end: 0, id: ++this.speakId, replace: false, lead });+ }+beatHit(id: string, note?: number, accent?: number): void {this.send({ type: "beatHit", id, note, accent });}diff --git a/src/engine/control/score.ts b/src/engine/control/score.tsindex 11ef3b0..72d7ca6 100644--- a/src/engine/control/score.ts+++ b/src/engine/control/score.ts@@ -17,7 +17,9 @@ export type SourceKey =/** breath pressure multiplier (0 = no breath, 1 = performer's pressure, <0 = ingressive) */| "breath"/** pitch in Hz (absolute) */- | "f0";+ | "f0"+ /** vibrato depth (cents): singers let it bloom a few hundred ms into a held note */+ | "vibrato";export type ControlKey = ArticKey | SourceKey;@@ -33,6 +35,8 @@ export interface Gesture {releaseHold?: number;/** label for visualisation (phoneme / gesture name) */label?: string;+ /** open-ended gestures (a sung note held until its key is released) end via release(tag) */+ tag?: number;}export interface Blended {@@ -75,6 +79,17 @@ export class GestureScore {this.end = 0;}+ /** End every gesture with this tag at time t (those already ended are left alone). */+ release(tag: number, t: number): void {+ for (const g of this.gestures)+ if (g.tag === tag && g.t1 > t) {+ g.t1 = Math.max(g.t0, t);+ }+ let end = 0;+ for (const g of this.gestures) end = Math.max(end, g.t1 + g.rampOut + (g.releaseHold ?? 0));+ this.end = end;+ }+/** Drop gestures that have fully finished before time t. */prune(t: number): void {if (this.gestures.length === 0) return;diff --git a/src/engine/phonetics/english.ts b/src/engine/phonetics/english.tsindex 9ec5a9f..135e8bc 100644--- a/src/engine/phonetics/english.ts+++ b/src/engine/phonetics/english.ts@@ -93,13 +93,13 @@ export class EnglishG2P {return phrases;}- /** One word → segments with lexical stress. */- word(w: string): Segment[] {+ /** One word → segments with lexical stress. `reduce`: weak forms of function words (speech). */+ word(w: string, reduce = true): Segment[] {const clean = w.toLowerCase().replace(/^'+|'+$/g, "");const entry = this.dict?.get(clean);if (entry) {const segs = arpabetToSegments(entry);- if (FUNCTION_WORDS.has(clean)) {+ if (reduce && FUNCTION_WORDS.has(clean)) {const nv = segs.filter((s) => VOWELS.has(s.ipa)).length;for (const s of segs) {s.stress = 0;@@ -110,7 +110,7 @@ export class EnglishG2P {return segs;}// hyphenated compounds- if (clean.includes("-")) return clean.split("-").flatMap((p) => this.word(p));+ if (clean.includes("-")) return clean.split("-").flatMap((p) => this.word(p, reduce));return letterToSound(clean);}}diff --git a/src/engine/phonetics/planner.ts b/src/engine/phonetics/planner.tsindex d7f06f0..5081de2 100644--- a/src/engine/phonetics/planner.ts+++ b/src/engine/phonetics/planner.ts@@ -61,6 +61,12 @@ const EXPAND: Record<string, string[]> = {ɚ: ["ɝ"],};+/** The two vowel targets of a diphthong ("aɪ" → ["a", "ɪ"]), or null. */+export function diphthongParts(ipa: string): [string, string] | null {+ const p = EXPAND[ipa];+ return p && p.length === 2 ? [p[0], p[1]] : null;+}+export function isVowel(ipa: string, body = "male"): boolean {return !!VT[body]?.[ipa] || ipa in EXPAND;}diff --git a/src/engine/phonetics/sing.ts b/src/engine/phonetics/sing.tsnew file mode 100644index 0000000..1dc3546--- /dev/null+++ b/src/engine/phonetics/sing.ts@@ -0,0 +1,146 @@+/**+ * Singing: syllables on notes, through the same gestural planner as speech.+ * - A note's vowel lands on the beat. Its onset consonants are sung just before it (they take+ * their time from the previous note, as singers do), its coda just before the next onset.+ * - Diphthongs sustain their first vowel and glide to the second at the end of the note.+ * - A melisma ("-") carries the vowel onto further notes; the coda waits for the last of them.+ * - Vibrato blooms a quarter of a second into a held vowel.+ * Live playing uses open-ended notes: a key press sings the onset and starts a vowel that lasts+ * until the key is released (tagged gestures, ended with GestureScore.release), and the release+ * sings the glide and the coda.+ */+import { planUtterance, diphthongParts, type Plan, type PlannedSegment, type Segment } from "./planner.ts";+import { phoneme } from "./inventory.ts";+import type { Gesture } from "../control/score.ts";+import type { Syllable } from "./syllables.ts";++export const midiToHz = (m: number): number => 440 * Math.pow(2, (m - 69) / 12);++/** sung consonants are a little shorter than spoken ones */+const cdur = (ipa: string, body: string, k = 0.8) => (phoneme(ipa, body)?.dur ?? 0.07) * k;+const consonants = (segs: Segment[], body: string, k = 0.8): Segment[] => segs.map((c) => ({ ipa: c.ipa, dur: cdur(c.ipa, body, k) }));+const total = (segs: Segment[]) => segs.reduce((s, c) => s + (c.dur ?? 0), 0);++const vibratoGesture = (t0: number, t1: number, depth: number, tag?: number): Gesture => ({ t0: t0 + 0.22, t1, rampIn: 0.3, rampOut: 0.06, strength: 4, targets: { vibrato: depth }, label: "vibrato", tag });++export interface SungNote {+ midi: number;+ /** length in beats */+ beats: number;+ syl: Syllable;+}++export interface SongOptions {+ body: string;+ bpm: number;+ /** plan time of the first note's beat (its onset consonants come before) */+ t0: number;+ /** vibrato depth (cents) on held vowels */+ vibrato: number;+}++/** Plan a whole melody: one utterance per phrase, so each phrase gets its own breath. */+export function planSong(notes: SungNote[], o: SongOptions): Plan {+ const beat = 60 / o.bpm;+ const gestures: Gesture[] = [];+ const segments: PlannedSegment[] = [];+ const times: number[] = [];+ let t = o.t0;+ for (const n of notes) {+ times.push(t);+ t += n.beats * beat;+ }+ let end = t;+ let i = 0;+ while (i < notes.length) {+ let j = i;+ while (j < notes.length - 1 && !notes[j].syl.phraseEnd) j++;+ const segs: Segment[] = [];+ const vowelSpans: [number, number][] = [];+ const onsetOf = (k: number) => (notes[k].syl.melisma ? [] : consonants(notes[k].syl.onset, o.body));+ for (let k = i; k <= j; k++) {+ const n = notes[k];+ const hz = midiToHz(n.midi);+ const nextMelisma = k < j && notes[k + 1].syl.melisma;+ const coda = nextMelisma ? [] : consonants(lastOfChain(notes, k).coda, o.body);+ const onset = onsetOf(k);+ // vowel from this note's beat to the next note's onset (less this note's coda);+ // the phrase's last vowel leaves a short breath before the next phrase+ const noteEnd = k < j ? times[k + 1] - total(onsetOf(k + 1)) : times[j] + notes[j].beats * beat - Math.min(0.12, 0.3 * notes[j].beats * beat);+ const vdur = Math.max(0.05, noteEnd - times[k] - total(coda));+ segs.push(...onset);+ const parts = diphthongParts(n.syl.nucleus.ipa);+ if (parts && !nextMelisma) {+ segs.push({ ipa: parts[0], dur: vdur * 0.8, f0: hz, stress: 1 }, { ipa: parts[1], dur: vdur * 0.2, f0: hz, stress: 1 });+ } else segs.push({ ipa: parts ? parts[0] : n.syl.nucleus.ipa, dur: vdur, f0: hz, stress: 1 });+ segs.push(...coda);+ vowelSpans.push([times[k], times[k] + vdur]);+ }+ if (segs.length) {+ // the planner lays segments out from t0 + 0.06: start so the first vowel lands on its beat+ const plan = planUtterance(segs, { body: o.body, t0: times[i] - total(onsetOf(i)) - 0.06, f0: midiToHz(notes[i].midi), intonation: "flat" });+ gestures.push(...plan.gestures);+ segments.push(...plan.segments);+ for (const [a, b] of vowelSpans) if (b - a > 0.3) gestures.push(vibratoGesture(a, b, o.vibrato));+ end = Math.max(end, plan.end);+ }+ i = j + 1;+ }+ return { gestures, segments, end };+}++/** The syllable whose coda ends a melisma chain starting at note k. */+function lastOfChain(notes: SungNote[], k: number): Syllable {+ let b = k;+ while (b > 0 && notes[b].syl.melisma) b--;+ return notes[b].syl;+}++/** Live: gestures relative to "now" (the planner's 60 ms lead is mostly taken back). */+const LIVE_T0 = -0.045;+/** a held vowel lasts at most this long (s) */+const HOLD = 30;++/**+ * Key pressed: sing the previous syllable's glide and coda if it is still sounding (legato),+ * then this syllable's onset, then its vowel held open-ended. Every gesture gets `tag`; the+ * pitch and vibrato get `tag + 1`, so a melisma can change pitch without ending the vowel.+ */+export function planNoteOn(syl: Syllable, midi: number, o: { body: string; vibrato: number; tag: number; legatoFrom?: { syl: Syllable; midi: number } }): Gesture[] {+ const hz = midiToHz(midi);+ const segs: Segment[] = [];+ if (o.legatoFrom) segs.push(...tail(o.legatoFrom.syl, o.body, midiToHz(o.legatoFrom.midi)));+ segs.push(...consonants(syl.onset, o.body, 0.7));+ const parts = diphthongParts(syl.nucleus.ipa);+ segs.push({ ipa: parts ? parts[0] : syl.nucleus.ipa, dur: HOLD, f0: hz, stress: 1 });+ const plan = planUtterance(segs, { body: o.body, t0: LIVE_T0, f0: hz, intonation: "flat" });+ const vowel = plan.segments[plan.segments.length - 1];+ const out: Gesture[] = plan.gestures.map((g) => ({ ...g, tag: g.targets.f0 !== undefined ? o.tag + 1 : o.tag }));+ out.push(vibratoGesture(vowel.t0, vowel.t1, o.vibrato, o.tag + 1));+ return out;+}++/** Melisma, live: the held vowel moves to a new pitch (release tag + 1 first). */+export function planMelisma(midi: number, o: { vibrato: number; tag: number }): Gesture[] {+ return [+ { t0: 0, t1: HOLD, rampIn: 0.05, rampOut: 0.06, strength: 6, targets: { f0: midiToHz(midi) }, label: "pitch", tag: o.tag + 1 },+ vibratoGesture(0, HOLD, o.vibrato, o.tag + 1),+ ];+}++/** Key released: the diphthong's glide and the coda (release the note's tags first). */+export function planNoteOff(syl: Syllable, midi: number, body: string): Gesture[] {+ const hz = midiToHz(midi);+ const segs = tail(syl, body, hz);+ if (!segs.length) return [];+ return planUtterance(segs, { body, t0: LIVE_T0, f0: hz, intonation: "flat" }).gestures;+}++/** What follows a held vowel: the diphthong's glide (at the note's pitch) and the coda. */+function tail(syl: Syllable, body: string, hz: number): Segment[] {+ const parts = diphthongParts(syl.nucleus.ipa);+ const out: Segment[] = [];+ if (parts) out.push({ ipa: parts[1], dur: 0.07, stress: 1, f0: hz });+ out.push(...consonants(syl.coda, body, 0.7));+ return out;+}diff --git a/src/engine/phonetics/songs.ts b/src/engine/phonetics/songs.tsnew file mode 100644index 0000000..36cc1a3--- /dev/null+++ b/src/engine/phonetics/songs.ts@@ -0,0 +1,36 @@+/** Demo melodies for Sing mode: [MIDI note, beats] per syllable, in the adult female register. */+export interface DemoSong {+ name: string;+ bpm: number;+ lyrics: string;+ notes: [number, number][];+ /** octave shift per body */+ octave: { male: number; female: number; child: number };+}++export const DEMO_SONGS: DemoSong[] = [+ {+ // an original tune for this instrument+ name: "Made of air",+ bpm: 84,+ lyrics: "Breathe in, breathe out, I am made of air. Tongue and lips and throat, singing anywhere.",+ notes: [+ [64, 1], [60, 1], [62, 1], [57, 1],+ [57, 0.5], [60, 0.5], [64, 1], [62, 0.5], [60, 1.5],+ [65, 1], [64, 0.5], [62, 0.5], [60, 0.5], [62, 1.5],+ [64, 0.5], [62, 0.5], [60, 0.5], [59, 0.5], [57, 2],+ ],+ octave: { male: -1, female: 0, child: 0 },+ },+ {+ // traditional (public domain)+ name: "Twinkle, twinkle",+ bpm: 100,+ lyrics: "Twinkle twinkle little star, how I wonder what you are.",+ notes: [+ [60, 1], [60, 1], [67, 1], [67, 1], [69, 1], [69, 1], [67, 2],+ [65, 1], [65, 1], [64, 1], [64, 1], [62, 1], [62, 1], [60, 2],+ ],+ octave: { male: -1, female: 0, child: 0 },+ },+];diff --git a/src/engine/phonetics/syllables.ts b/src/engine/phonetics/syllables.tsnew file mode 100644index 0000000..ac36cc7--- /dev/null+++ b/src/engine/phonetics/syllables.ts@@ -0,0 +1,123 @@+/**+ * Lyrics → sung syllables. Words come from the pronouncing dictionary (unreduced: sung function+ * words keep full vowels), are split into syllables by the maximal-onset principle with English+ * onset clusters, and the spelling is split to match for display ("twin-kle").+ * Typed hyphens force syllable breaks; a lone "-" (or "~") holds the previous vowel onto the+ * next note (melisma), as in vocaloid editors.+ */+import type { Segment } from "./planner.ts";+import { isVowel } from "./planner.ts";++export interface Syllable {+ /** lyric text shown on the note */+ text: string;+ onset: Segment[];+ /** vowel (a diphthong stays one nucleus: "aɪ") */+ nucleus: Segment;+ coda: Segment[];+ /** continue the previous syllable's vowel at a new pitch */+ melisma?: boolean;+ /** last syllable of a word (codas sound here; phrase breaks follow punctuation) */+ wordEnd: boolean;+ /** a breath follows (comma, full stop, line break) */+ phraseEnd: boolean;+}++// English onsets (IPA), longest first matters only for the search below+const ONSETS = new Set([+ "p", "b", "t", "d", "k", "g", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h", "m", "n", "l", "ɹ", "w", "j", "tʃ", "dʒ",+ "pl", "bl", "kl", "gl", "fl", "sl", "pɹ", "bɹ", "tɹ", "dɹ", "kɹ", "gɹ", "fɹ", "θɹ", "ʃɹ",+ "sp", "st", "sk", "sm", "sn", "sw", "sf", "tw", "kw", "dw", "gw", "θw",+ "pj", "bj", "kj", "gj", "mj", "nj", "fj", "vj", "hj", "lj",+ "spl", "spɹ", "stɹ", "skɹ", "skw", "skj", "spj",+]);++/** Split one word's segments into onset / nucleus / coda syllables. */+export function syllabifySegments(segs: Segment[]): { onset: Segment[]; nucleus: Segment; coda: Segment[] }[] {+ const vi = segs.map((s, i) => (isVowel(s.ipa) ? i : -1)).filter((i) => i >= 0);+ if (!vi.length) return [];+ const out: { onset: Segment[]; nucleus: Segment; coda: Segment[] }[] = [];+ let start = 0;+ vi.forEach((v, n) => {+ const next = vi[n + 1];+ let end = segs.length; // exclusive end of this syllable+ if (next !== undefined) {+ // consonants between this vowel and the next: the longest legal onset goes right+ const between = segs.slice(v + 1, next);+ let k = 0;+ for (let len = Math.min(3, between.length); len >= 1; len--) {+ if (ONSETS.has(between.slice(between.length - len).map((s) => s.ipa).join(""))) {+ k = len;+ break;+ }+ }+ end = next - k;+ }+ out.push({ onset: segs.slice(start, v), nucleus: segs[v], coda: segs.slice(v + 1, end) });+ start = end;+ });+ return out;+}++const V = /[aeiouy]+/g;++/** Split a written word into n chunks at its vowel groups (approximate hyphenation). */+export function splitSpelling(word: string, n: number): string[] {+ if (n <= 1) return [word];+ const groups: [number, number][] = [];+ for (const m of word.toLowerCase().matchAll(V)) groups.push([m.index!, m.index! + m[0].length]);+ // a final silent e ("like") is not a syllable, but consonant + "le" is ("twin-kle", "lit-tle")+ if (groups.length > 1 && /[^aeiouy]e$/i.test(word) && !/[^aeiouyl]le$/i.test(word) && groups[groups.length - 1][0] === word.length - 1) groups.pop();+ if (groups.length < n) {+ // fewer written vowels than sung syllables (e.g. "fire"): hold the word, then continue marks+ return [word, ...Array(n - 1).fill("~")];+ }+ while (groups.length > n) {+ const last = groups.pop()!;+ groups[groups.length - 1][1] = last[1];+ }+ const cuts: number[] = [0];+ for (let i = 0; i < groups.length - 1; i++) {+ const a = groups[i][1], b = groups[i + 1][0]; // consonant letters a..b between vowel groups+ // a digraph stays together on the right ("any-where", "fa-ther"); otherwise one consonant+ // goes right and longer runs split in the middle ("lit-tle", "won-der")+ const gap = b - a;+ const dig = gap >= 2 && /^(th|sh|ch|ph|wh|ck|gh)$/i.test(word.slice(b - 2, b));+ cuts.push(dig ? b - 2 : a + (gap <= 1 ? 0 : Math.floor(gap / 2)));+ }+ cuts.push(word.length);+ return cuts.slice(0, -1).map((c, i) => word.slice(c, cuts[i + 1]));+}++export interface WordSource {+ word(w: string, reduce?: boolean): Segment[];+}++/** Lyrics text → syllables (needs the pronouncing dictionary for real words). */+export function lyricsToSyllables(text: string, g2p: WordSource): Syllable[] {+ const out: Syllable[] = [];+ // words, melisma marks and phrase punctuation, in order+ const tokens = text.replace(/[’']/g, "'").match(/[A-Za-z'][A-Za-z'\-]*|(?<=\s|^)[~-](?=\s|$)|[.,;:!?\n]/g) ?? [];+ for (const tok of tokens) {+ if (/^[.,;:!?\n]$/.test(tok)) {+ if (out.length) out[out.length - 1].phraseEnd = true;+ continue;+ }+ if (tok === "-" || tok === "~") {+ const prev = out[out.length - 1];+ if (prev) out.push({ text: "~", onset: [], nucleus: prev.nucleus, coda: [], melisma: true, wordEnd: prev.wordEnd, phraseEnd: false });+ continue;+ }+ // typed hyphens split syllables explicitly ("ti-ger"); otherwise the dictionary decides+ const parts = tok.split("-").filter(Boolean);+ const syls: Syllable[] = [];+ for (const part of parts) {+ const sy = syllabifySegments(g2p.word(part.toLowerCase(), false));+ const spell = parts.length > 1 ? [part, ...Array(Math.max(0, sy.length - 1)).fill("~")] : splitSpelling(part, sy.length);+ sy.forEach((s, i) => syls.push({ ...s, text: spell[i] ?? "~", wordEnd: false, phraseEnd: false }));+ }+ if (syls.length) syls[syls.length - 1].wordEnd = true;+ out.push(...syls);+ }+ return out;+}diff --git a/src/engine/voice/humanVoice.ts b/src/engine/voice/humanVoice.tsindex 41f7a68..d9e4e08 100644--- a/src/engine/voice/humanVoice.ts+++ b/src/engine/voice/humanVoice.ts@@ -125,6 +125,8 @@ export class HumanVoice {this.dec = new Decimator(this.M);this.ctrlEvery = 64 * this.M;this.dcCoef = Math.exp((-2 * Math.PI * 25) / this.fsOut);+ this.limHoldN = Math.round(0.025 * this.fsOut);+ this.limRelease = Math.exp(-1 / (0.2 * this.fsOut));const nTract = this.airway.nPh + this.airway.nOr;this.rmsAcc = new Float64Array(nTract);this.flowSm = new Float64Array(nTract);@@ -150,6 +152,11 @@ export class HumanVoice {this.score.addAll(gestures);}+ /** End the open-ended gestures with this tag now (a sung note's key was released). */+ release(tag: number): void {+ this.score.release(tag, this.clock);+ }+/** Cancel scheduled gestures (speech stops; the voice returns to the performer's posture). */cancelScore(): void {this.score.clear();@@ -182,6 +189,11 @@ export class HumanVoice {g.effort = clamp((Math.abs(s.pressure) - 3) / 10, 0, 1);}+ private limEnv = 0;+ private limHold = 0;+ private readonly limHoldN: number;+ private readonly limRelease: number;+/** Render n output samples into out[offset..]. */render(out: Float32Array, offset: number, n: number): void {const air = this.airway;@@ -213,9 +225,18 @@ export class HumanVoice {this.dcX = v;this.dcY = hp;v = hp;- // soft limiter+ // output limiter: a peak envelope held for longer than a glottal period, so a loud+ // sung vowel is turned down by a steady gain instead of being squared off; only a+ // rising level touches the soft clipconst av = Math.abs(v);- if (av > 0.7) v = Math.sign(v) * (0.7 + 0.3 * Math.tanh((av - 0.7) / 0.3));+ if (av >= this.limEnv) {+ this.limEnv = av;+ this.limHold = this.limHoldN;+ } else if (this.limHold > 0) this.limHold--;+ else this.limEnv *= this.limRelease;+ if (this.limEnv > 0.75) v *= 0.75 / this.limEnv;+ const al = Math.abs(v);+ if (al > 0.85) v = Math.sign(v) * (0.85 + 0.15 * Math.tanh((al - 0.85) / 0.15));out[offset + i] = v;this.outAcc += v * v;this.outCount++;@@ -269,6 +290,8 @@ export class HumanVoice {breathAct = Math.min(1, br.weight);breathVal = br.value;}+ const vb = score.blend("vibrato", t, tmp);+ gp.vibratoDepth = vb.weight > 0 ? (this.source.vibratoDepth * 0.05 + vb.value * vb.weight) / (0.05 + vb.weight) : this.source.vibratoDepth;const pf = score.blend("f0", t, tmp);if (pf.weight > 0) {f0Target = (this.source.f0 * 0.02 + pf.value * pf.weight) / (0.02 + pf.weight);diff --git a/src/worklet/processor.ts b/src/worklet/processor.tsindex 93d298b..0b15b2f 100644--- a/src/worklet/processor.ts+++ b/src/worklet/processor.ts@@ -90,7 +90,7 @@ class ChimeraProcessor extends AudioWorkletProcessor {break;case "schedule": {// O(n) time shift onto the voice clock; planning happened on the main thread- const off = this.voice.clock + 0.03;+ const off = this.voice.clock + (m.lead ?? 0.03);const gs = m.gestures.slice(0, 4000);for (const g of gs) {g.t0 += off;@@ -98,7 +98,7 @@ class ChimeraProcessor extends AudioWorkletProcessor {}if (m.replace) this.voice.cancelScore();this.voice.schedule(gs);- this.post({ type: "planned", id: m.id, t0: off, end: m.end + off, segments: m.segments.map((s) => ({ ...s, t0: s.t0 + off, t1: s.t1 + off })) });+ if (m.segments.length) this.post({ type: "planned", id: m.id, t0: off, end: m.end + off, segments: m.segments.map((s) => ({ ...s, t0: s.t0 + off, t1: s.t1 + off })) });break;}case "stopSpeech":@@ -116,6 +116,9 @@ class ChimeraProcessor extends AudioWorkletProcessor {}break;}+ case "release":+ this.voice.release(m.tag);+ 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));diff --git a/src/worklet/protocol.ts b/src/worklet/protocol.tsindex f4b60a3..a962104 100644--- a/src/worklet/protocol.ts+++ b/src/worklet/protocol.ts@@ -21,7 +21,7 @@ export type ToWorklet =| { type: "gate"; level: number }| { type: "telemetry"; enabled: boolean }/** gestures planned on the main thread with times relative to "now" (the worklet adds its clock) */- | { type: "schedule"; gestures: Gesture[]; segments: PlannedSegment[]; end: number; id: number; replace: boolean }+ | { type: "schedule"; gestures: Gesture[]; segments: PlannedSegment[]; end: number; id: number; replace: boolean; lead?: number }| { type: "stopSpeech" }/** switch the active voice: "human" or a creature id */| { type: "creature"; id: string; params?: Record<string, number> }@@ -30,6 +30,8 @@ export type ToWorklet =| { type: "stopCall" }/** beatbox sequencer: any subset of its state */| { type: "beat"; steps?: (BeatStep | null)[]; bpm?: number; swing?: number; playing?: boolean }+ /** end the open-ended gestures with this tag now (a sung note released) */+ | { type: "release"; tag: number }/** play one beatbox sound as soon as the mouth can make it */| { type: "beatHit"; id: string; note?: number; accent?: number };diff --git a/tests/syllables.test.ts b/tests/syllables.test.tsnew file mode 100644index 0000000..630c3ba--- /dev/null+++ b/tests/syllables.test.ts@@ -0,0 +1,48 @@+import { describe, expect, test } from "bun:test";+import { arpabetToSegments } from "../src/engine/phonetics/english.ts";+import { lyricsToSyllables, splitSpelling, syllabifySegments } from "../src/engine/phonetics/syllables.ts";++// a few CMUdict entries, enough to test without loading the dictionary+const DICT: Record<string, string> = {+ twinkle: "T W IH1 NG K AH0 L",+ little: "L IH1 T AH0 L",+ star: "S T AA1 R",+ how: "HH AW1",+ i: "AY1",+ wonder: "W AH1 N D ER0",+ what: "W AH1 T",+ you: "Y UW1",+ are: "AA1 R",+ extra: "EH1 K S T R AH0",+ of: "AH1 V",+};+const g2p = { word: (w: string) => (DICT[w] ? arpabetToSegments(DICT[w]) : []) };+const ipa = (xs: { ipa: string }[]) => xs.map((x) => x.ipa).join("");++describe("syllables", () => {+ test("maximal onset with legal English clusters", () => {+ const tw = syllabifySegments(g2p.word("twinkle"));+ expect(tw.map((s) => [ipa(s.onset), s.nucleus.ipa, ipa(s.coda)])).toEqual([+ ["tw", "ɪ", "ŋ"],+ ["k", "ə", "l"],+ ]);+ // "extra": k + str → ek-stra (str is a legal onset)+ const ex = syllabifySegments(g2p.word("extra"));+ expect(ex.map((s) => ipa(s.onset))).toEqual(["", "stɹ"]);+ expect(ipa(ex[0].coda)).toBe("k");+ });+ test("spelling splits to match", () => {+ expect(splitSpelling("twinkle", 2)).toEqual(["twin", "kle"]);+ expect(splitSpelling("little", 2)).toEqual(["lit", "tle"]);+ expect(splitSpelling("wonder", 2)).toEqual(["won", "der"]);+ expect(splitSpelling("are", 1)).toEqual(["are"]);+ });+ test("lyrics: words, melisma, phrase ends, unreduced function words", () => {+ const syl = lyricsToSyllables("Twinkle little star, how I - wonder", g2p);+ expect(syl.map((s) => s.text)).toEqual(["Twin", "kle", "lit", "tle", "star", "how", "I", "~", "won", "der"]);+ expect(syl[4].phraseEnd).toBe(true);+ expect(syl[7].melisma).toBe(true);+ expect(syl[7].nucleus.ipa).toBe("aɪ");+ expect(syl[1].wordEnd && !syl[0].wordEnd).toBe(true);+ });+});diff --git a/tools/render-song.ts b/tools/render-song.tsnew file mode 100644index 0000000..cdd1d1a--- /dev/null+++ b/tools/render-song.ts@@ -0,0 +1,82 @@+/**+ * Render a sung melody through the real-time voice (the Sing mode's demo, or a live-style+ * key sequence), with a spectrogram.+ * Usage: bun tools/render-song.ts outdir [male|female|child]+ */+import { mkdirSync, readFileSync } from "node:fs";+import { gunzipSync } from "node:zlib";+import { HumanVoice } from "../src/engine/voice/humanVoice.ts";+import { BODY_MALE, BODY_FEMALE, BODY_CHILD } from "../src/engine/anatomy/human.ts";+import { EnglishG2P } from "../src/engine/phonetics/english.ts";+import { lyricsToSyllables } from "../src/engine/phonetics/syllables.ts";+import { planSong, planNoteOn, planNoteOff, midiToHz } from "../src/engine/phonetics/sing.ts";+import { DEMO_SONGS } from "../src/engine/phonetics/songs.ts";+import { writeWav } from "./lib/wav.ts";+import { renderSpectrogram } from "./lib/spectrogram.ts";++const outDir = process.argv[2] ?? "out/song";+const bodyName = (process.argv[3] ?? "male") as "male" | "female" | "child";+const body = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD }[bodyName];+mkdirSync(outDir, { recursive: true });+const FS = 48000;+const g2p = new EnglishG2P();+g2p.setDictionaryText(gunzipSync(readFileSync("public/data/cmudict.txt.gz")).toString("utf8"));++for (const song of DEMO_SONGS) {+ const syl = lyricsToSyllables(song.lyrics, g2p);+ const shift = song.octave[bodyName] * 12;+ const notes = song.notes.map((n, i) => ({ midi: n[0] + shift, beats: n[1], syl: syl[i % syl.length] }));+ const v = new HumanVoice({ fsOut: FS, body });+ v.setSource({ f0: midiToHz(notes[0].midi), voiced: true, pressure: 9, tension: 0.55 });+ const plan = planSong(notes, { body: bodyName, bpm: song.bpm, t0: 0.3, vibrato: 35 });+ v.schedule(plan.gestures);+ const N = Math.round(FS * (plan.end + 0.4));+ const out = new Float32Array(N);+ for (let i = 0; i < N; i += 128) v.render(out, i, Math.min(128, N - i));+ let pk = 0;+ for (const x of out) pk = Math.max(pk, Math.abs(x));+ const slug = song.name.toLowerCase().replace(/[^a-z]+/g, "-");+ writeWav(`${outDir}/${slug}-${bodyName}.wav`, [out], FS);+ const beat = 60 / song.bpm;+ let t = 0.3;+ const marks = notes.map((n) => { const m = { t, label: "" }; t += n.beats * beat; return m; });+ renderSpectrogram(`${outDir}/${slug}-${bodyName}.png`, out, FS, { title: `${song.name} (${bodyName})`, maxFreq: 6000, windowMs: 25, marks });+ console.log(`${song.name}: ${(N / FS).toFixed(1)} s, peak ${pk.toFixed(3)}, syllables ${syl.map((s) => s.text).join(" ")}`);+}++// live-style: key presses with gaps and one legato pair, as the keyboard would send them+{+ const syl = lyricsToSyllables("hello there my friend", g2p);+ const v = new HumanVoice({ fsOut: FS, body });+ v.setSource({ f0: 130, voiced: true, pressure: 9 });+ const keys: [number, number, number][] = [[0.2, 0.55, 57], [0.6, 1.0, 59], [1.1, 1.8, 62], [1.75, 2.6, 60]]; // [down, up, midi]+ const N = Math.round(FS * 3);+ const out = new Float32Array(N);+ let tag = 2;+ let held: { syl: (typeof syl)[number]; midi: number; tag: number; up: number } | null = null;+ const events = keys.flatMap(([d, u, m], i) => [{ t: d, on: true, m, i }, { t: u, on: false, m, i }]).sort((a, b) => a.t - b.t);+ let e = 0;+ for (let i = 0; i < N; i += 128) {+ const now = v.clock;+ while (e < events.length && events[e].t <= now) {+ const ev = events[e++];+ const shift = (gs: import("../src/engine/control/score.ts").Gesture[]) => gs.map((g) => ({ ...g, t0: g.t0 + now + 0.006, t1: g.t1 + now + 0.006 }));+ if (ev.on) {+ const s = syl[ev.i];+ if (held) v.release(held.tag), v.release(held.tag + 1);+ v.schedule(shift(planNoteOn(s, ev.m, { body: bodyName, vibrato: 35, tag, legatoFrom: held ? { syl: held.syl, midi: held.midi } : undefined })));+ held = { syl: s, midi: ev.m, tag, up: 0 };+ tag += 2;+ } else if (held && held.midi === ev.m) {+ v.release(held.tag);+ v.release(held.tag + 1);+ v.schedule(shift(planNoteOff(held.syl, held.midi, bodyName)));+ held = null;+ }+ }+ v.render(out, i, Math.min(128, N - i));+ }+ writeWav(`${outDir}/live-${bodyName}.wav`, [out], FS);+ renderSpectrogram(`${outDir}/live-${bodyName}.png`, out, FS, { title: `live: hello there my friend (${bodyName})`, maxFreq: 6000, windowMs: 25, marks: keys.map(([d]) => ({ t: d, label: "" })) });+ console.log(`live: syllables ${syl.map((s) => s.text).join(" ")}`);+}