the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Speech ends in silence: no drone in Speak, no added vowel after final consonants, no tick
Jameson Hodgee00bac5b4aa0
diff --git a/src/engine/anatomy/human.ts b/src/engine/anatomy/human.tsindex d511b70..6f0884b 100644--- a/src/engine/anatomy/human.ts+++ b/src/engine/anatomy/human.ts@@ -431,7 +431,11 @@ export class HumanVocalTract {const near = 1 - smoothstep(win, 2 * win, ad);const regime = 1 - smoothstep(0.15 * k, 0.6 * k, c.d);const w = near * regime;- const dm = Math.min(g.d, dc);+ // the parabola also caps the ray gap; the cap fades out at the edges of the window and+ // of the contact regime, so the gap stays continuous as the tongue moves (a cap that+ // switched on at full strength made the area jump, heard as a tick)+ const cap = (1 - smoothstep(1.5 * win, 2 * win, ad)) * (1 - smoothstep(0.45 * k, 0.6 * k, c.d));+ const dm = g.d + (Math.min(g.d, dc) - g.d) * cap;g.d = dm + (dc - dm) * w;};for (const g of grid) {diff --git a/src/engine/phonetics/planner.ts b/src/engine/phonetics/planner.tsindex d47867e..1b47fe2 100644--- a/src/engine/phonetics/planner.ts+++ b/src/engine/phonetics/planner.ts@@ -33,6 +33,8 @@ export interface PlanOptions {intonation?: "statement" | "question" | "flat";/** pitch excursion for stressed syllables (fraction) */accent?: number;+ /** the last segment is held open-ended (a sung note): no end-of-breath release */+ openEnd?: boolean;}export interface PlannedSegment {@@ -199,7 +201,16 @@ export function planUtterance(input: Segment[], o: PlanOptions): Plan {void prevVowel;});// ---- breath: on through the utterance- gestures.push({ t0: o.t0 + 0.04, t1: end, rampIn: 0.04, rampOut: 0.07, strength: 1, targets: { breath: 1 }, label: "breath" });+ gestures.push({ t0: o.t0 + 0.04, t1: end, rampIn: 0.04, rampOut: o.openEnd ? 0.07 : 0.05, strength: 1, targets: { breath: 1 }, label: "breath" });+ // ---- end of the breath group: the folds part as the breath stops, so a final obstruent is+ // released into silence instead of into an added vowel ("cat-uh"). After a vowel or sonorant+ // they part once the pressure has fallen, so the voice fades out instead of ending in an [h].+ if (!o.openEnd) {+ const last = segs[segs.length - 1];+ const sonorant = !!last?.vowel || ["nasal", "approximant", "lateral", "tap", "trill"].includes(last?.def?.manner ?? "");+ const at = end + (sonorant ? 0.045 : 0.015);+ gestures.push({ t0: at, t1: end + 0.1, rampIn: 0.03, rampOut: 0.06, strength: 6, targets: { abduction: 0.22 }, label: "exhale" });+ }// ---- intonation: pitch targets on vowelsconst f0 = o.f0 ?? 110;const accent = o.accent ?? 0.14;diff --git a/src/engine/phonetics/sing.ts b/src/engine/phonetics/sing.tsindex 1dc3546..261943c 100644--- a/src/engine/phonetics/sing.ts+++ b/src/engine/phonetics/sing.ts@@ -113,7 +113,7 @@ export function planNoteOn(syl: Syllable, midi: number, o: { body: string; vibrasegs.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 plan = planUtterance(segs, { body: o.body, t0: LIVE_T0, f0: hz, intonation: "flat", openEnd: true });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));diff --git a/src/engine/voice/humanVoice.ts b/src/engine/voice/humanVoice.tsindex d9e4e08..a552bb7 100644--- a/src/engine/voice/humanVoice.ts+++ b/src/engine/voice/humanVoice.ts@@ -89,6 +89,8 @@ export class HumanVoice {/** breath gate 0..1 (note on/off) */gate = 0;private gateTarget = 0;+ /** time left (s) during which a release of the gate follows the score's own breath ramp */+ private scoreBreathHold = 0;private pLung = 0;private f0 = DEFAULT_SOURCE.f0;outputGain = 5.5e-7;@@ -314,9 +316,11 @@ export class HumanVoice {// a negative breath gesture (ingressive: inward K snares, gasps) overrides the performer's breathconst scoreBreath = breathVal * breathAct;const gateGoal = scoreBreath < 0 ? scoreBreath : Math.max(this.gateTarget, scoreBreath);- // a score shapes its own breath ramps (beatbox hits end their breath abruptly); the slow+ // a score shapes its own breath ramps (beatbox hits end their breath abruptly, phrases end+ // into silence), including the moments just after its breath gesture has ended; the slow// release is for the performer's note-offs- const tau = gateGoal > this.gate ? 0.025 : breathAct > 0 ? 0.02 : 0.07;+ this.scoreBreathHold = breathAct > 0 ? 0.15 : Math.max(0, this.scoreBreathHold - dt);+ 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;// pitch glidediff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 865e26c..e51ac9d 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -112,7 +112,8 @@ function StartPrompt() {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."];+ 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."];return (<div className="start-prompt"><p>{copy[0]}</p>@@ -124,7 +125,7 @@ function StartPrompt() {const first = creatureById(creature)?.calls[0];if (mode === "bestiary" && first) playCall(first.id);else if (mode === "beatbox") setBeatPlaying(true);- else setHold(true);+ else if (mode === "play") setHold(true);}}>{starting ? "Starting…" : copy[1]}diff --git a/src/ui/store.ts b/src/ui/store.tsindex ef19193..66694ba 100644--- a/src/ui/store.ts+++ b/src/ui/store.ts@@ -132,6 +132,8 @@ 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 (m === "beatbox") {// a beatboxer waits with the jaw nearly closed; the sounds bring their own breathset({ hold: false });diff --git a/tests/speech-quality.test.ts b/tests/speech-quality.test.tsindex 4c1b274..63b1dc6 100644--- a/tests/speech-quality.test.ts+++ b/tests/speech-quality.test.ts@@ -2,21 +2,32 @@ import { describe, expect, test } from "bun:test";import { HumanVoice } from "../src/engine/voice/humanVoice.ts";import { planUtterance } from "../src/engine/phonetics/planner.ts";import { tokenizeIpa } from "../src/engine/phonetics/ipa.ts";+import { HumanVocalTract, NEUTRAL, BODY_MALE } from "../src/engine/anatomy/human.ts";const FS = 48000;-function render(ipa: string) {+function render(ipa: string, tail = 0.15) {const v = new HumanVoice({ fsOut: FS });const plan = planUtterance(tokenizeIpa(ipa), { body: "male", t0: 0.05, f0: 110 });v.schedule(plan.gestures);- const N = Math.round(FS * (plan.end + 0.15));+ const N = Math.round(FS * (plan.end + tail));const out = new Float32Array(N);- const port: number[] = [];+ const port: number[] = [], voicing: number[] = [];for (let i = 0; i < N; i += 128) {v.render(out, i, Math.min(128, N - i));port.push(v.airway.frame?.velumPort ?? 0);+ voicing.push(v.glottis.voicing);}- return { plan, port, at: (t: number) => port[Math.min(port.length - 1, Math.round((t * FS) / 128))] };+ const frame = (t: number) => Math.min(port.length - 1, Math.round((t * FS) / 128));+ return { plan, out, port, voicing, frame, at: (t: number) => port[frame(t)] };+}++/** RMS level (dB re the utterance's peak) over [t0, t1). */+function levelDb(out: Float32Array, t0: number, t1: number): number {+ let peak = 0, e = 0, n = 0;+ for (const x of out) peak = Math.max(peak, Math.abs(x));+ for (let i = Math.round(t0 * FS); i < Math.min(out.length, Math.round(t1 * FS)); i++, n++) e += out[i] * out[i];+ return 20 * Math.log10(Math.sqrt(e / Math.max(1, n)) / peak + 1e-12);}describe("running-speech quality guards", () => {@@ -38,4 +49,35 @@ describe("running-speech quality guards", () => {expect(d(last) / d(first)).toBeGreaterThan(1.25);expect(d(first) / d(mid)).toBeGreaterThan(1.4);});+ test("a phrase ends in silence: no vowel added after a final consonant, no lingering breath", () => {+ for (const ipa of ["ˈbæd", "ˈkæt", "ˈsi", "ˈðɛm"]) {+ const { plan, out, voicing, frame } = render(ipa, 0.45);+ const final = plan.segments[plan.segments.length - 1];+ const sonorant = final.kind === "vowel" || final.kind === "nasal";+ // the folds stop at a final obstruent's release; a final vowel or nasal fades out+ const voicedFor = sonorant ? 0.05 : 0.015;+ for (let f = frame(plan.end + voicedFor); f < voicing.length; f++) expect(voicing[f]).toBeLessThan(0.3);+ expect(levelDb(out, plan.end + 0.15, plan.end + 0.45)).toBeLessThan(-50);+ }+ });+});++describe("tract geometry continuity", () => {+ test("the tongue-palate contact model engages smoothly (no area jump as the gap closes past 6 mm)", () => {+ // the tongue on its way from a final /d/ back to rest: the body's gap to the roof crosses+ // the contact regime's edge (0.6 cm) at tbY ≈ 6.90+ const A = { ...NEUTRAL, jaw: 0.604, tbX: 2.935, ttX: 6.272, ttY: 6.89, lipAp: 0.703, lipProt: 0.2, lipWidth: 0.5 };+ const tract = new HumanVocalTract(BODY_MALE);+ const ph = new Float64Array(20), or = new Float64Array(24);+ let prev: number[] | null = null;+ let worst = 0;+ for (let y = 6.85; y <= 6.95; y += 0.001) {+ const a = { ...A, tbY: y };+ tract.resample(a, tract.compute(a), 20, 24, ph, or);+ const cur = [...ph, ...or];+ if (prev) for (let j = 0; j < cur.length; j++) worst = Math.max(worst, Math.abs(cur[j] - prev[j]));+ prev = cur;+ }+ expect(worst).toBeLessThan(0.05); // cm² per 0.01 mm of tongue travel (was 0.87 at the edge)+ });});diff --git a/tools/e2e.ts b/tools/e2e.tsindex 30a650d..a06bd20 100644--- a/tools/e2e.ts+++ b/tools/e2e.ts@@ -63,6 +63,19 @@ async function run(viewport: { width: number; height: number }, tag: string) {await page.screenshot({ path: `${outDir}/${tag}-3-speak.png`, fullPage: true });const trans = await page.locator(".transcription").textContent();logs.push(`[${tag}] transcription: ${trans}`);+ // speech breathes by itself: Play's held breath must not drone on once the phrase is over+ const speechRms: number[] = [];+ for (let i = 0; i < 12; i++) {+ await page.waitForTimeout(250);+ speechRms.push(+ await page.evaluate(() => {+ // @ts-expect-error debug handle+ return window.__chimeraEngine?.latest?.t?.outRms ?? -1;+ }),+ );+ }+ logs.push(`[${tag}] speech rms then silence ${speechRms.map((r) => r.toFixed(4)).join(",")}`);+ if (!(Math.max(...speechRms.slice(-3)) < 1e-3)) errors.push(`[${tag}] voice still sounding after the phrase: ${speechRms.slice(-3).join(",")}`);await page.locator("button.ipa", { hasText: "ʃ" }).first().click();await page.waitForTimeout(700);await page.screenshot({ path: `${outDir}/${tag}-4-pad.png` });@@ -132,4 +145,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/i.test(l)).slice(0, 40).join("\n"));+console.log(logs.filter((l) => /load|warn|transcription|creature|held|back to|beatbox|silence/i.test(l)).slice(0, 40).join("\n"));