Skip to content

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

Rust

Speak mode: English TTS (CMUdict + rules), IPA chart pads, gestural score view

Jameson Hodgecec69179c950
diff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.ts
index 3f8d495..c94267f 100644
--- a/src/audio/AudioEngine.ts
+++ b/src/audio/AudioEngine.ts
@@ -3,7 +3,7 @@
* parameter messages (at most one per animation frame per kind) and telemetry fan-out.
*/
import workletUrl from "../worklet/processor.ts?worker&url";
-import type { ToWorklet, FromWorklet, TelemetryMessage, BodyName } from "../worklet/protocol.ts";
+import type { ToWorklet, FromWorklet, TelemetryMessage, BodyName, PlannedMessage } from "../worklet/protocol.ts";
import type { HumanArtic } from "../engine/anatomy/human.ts";
import type { VoiceSource } from "../engine/voice/humanVoice.ts";
@@ -22,6 +22,10 @@ export class AudioEngine {
private pendingSource: Partial<VoiceSource> | null = null;
private flushScheduled = false;
private readyListeners = new Set<() => void>();
+ private plannedListeners = new Set<(p: PlannedMessage) => void>();
+ /** most recent planned utterance (for timelines) */
+ lastPlan: PlannedMessage | null = null;
+ private speakId = 0;
error: string | null = null;
get running(): boolean {
@@ -54,6 +58,9 @@ export class AudioEngine {
if (m.type === "telemetry") {
this.latest = m;
for (const l of this.listeners) l(m);
+ } else if (m.type === "planned") {
+ this.lastPlan = m;
+ for (const l of this.plannedListeners) l(m);
} else if (m.type === "ready") {
for (const l of this.readyListeners) l();
} else if (m.type === "error") {
@@ -69,6 +76,22 @@ export class AudioEngine {
return () => this.listeners.delete(l);
}
+ onPlanned(l: (p: PlannedMessage) => void): () => void {
+ this.plannedListeners.add(l);
+ return () => this.plannedListeners.delete(l);
+ }
+
+ /** Send a gestural plan (times relative to now). Returns the request id. */
+ schedule(plan: { gestures: import("../engine/control/score.ts").Gesture[]; segments: import("../engine/phonetics/planner.ts").PlannedSegment[]; end: number }, replace = true): number {
+ const id = ++this.speakId;
+ this.send({ type: "schedule", gestures: plan.gestures, segments: plan.segments, end: plan.end, id, replace });
+ return id;
+ }
+
+ stopSpeech(): void {
+ this.send({ type: "stopSpeech" });
+ }
+
onReady(l: () => void): () => void {
this.readyListeners.add(l);
return () => this.readyListeners.delete(l);
diff --git a/src/engine/airway/network.ts b/src/engine/airway/network.ts
index 350082a..5046d4e 100644
--- a/src/engine/airway/network.ts
+++ b/src/engine/airway/network.ts
@@ -137,6 +137,8 @@ export class AirwayNetwork {
/** nodes with ≥3 connections get a compliance floor for leapfrog stability */
private isJunction!: Uint8Array;
private invLsum!: Float64Array;
+ /** per-sample reciprocal minimum area (jet losses) */
+ private invAmin!: Float64Array;
/** neighbour lists (CSR) for redistributing squeezed volume of nearly closed nodes */
private nbrStart!: Int32Array;
private nbrList!: Int32Array;
@@ -303,6 +305,7 @@ export class AirwayNetwork {
this.aminStep = new Float64Array(N);
this.isJunction = new Uint8Array(N);
this.invLsum = new Float64Array(N);
+ this.invAmin = new Float64Array(N);
this.dx = new Float64Array(N);
this.dxTarget = new Float64Array(N);
this.dxStep = new Float64Array(N);
@@ -569,9 +572,11 @@ export class AirwayNetwork {
area[k] = a;
let am = amin[k] + this.aminStep[k];
if (am < 0) am = 0;
- amin[k] = am > a ? a : am;
+ const amk = am > a ? a : am;
+ amin[k] = amk;
const d = (dx[k] += this.dxStep[k]);
invA[k] = 1 / (a > 1e-6 ? a : 1e-6);
+ this.invAmin[k] = 1 / (amk > 1e-6 ? amk : 1e-6);
const v = (a > minA ? a : minA) * d;
if (volOn) {
const raw = -(v - vol[k]) * invT;
@@ -653,13 +658,14 @@ export class AirwayNetwork {
R = 0.5 * visc * (this.wallPerim[a] * dx[a] * Math.sqrt(Aa) * ia * ia * this.viscF[a] + this.wallPerim[b] * dx[b] * Math.sqrt(Ab) * ib * ib * this.viscF[b]);
// Borda–Carnot: the jet leaving the narrowest point of the upstream node expands into
// the downstream node (sub-section minima make short constrictions lossy as they should be)
- const ef = 1 / ma - ib; // a→b
- const eb = 1 / mb - ia; // b→a
+ const ima = this.invAmin[a], imb = this.invAmin[b];
+ const ef = ima - ib; // a→b
+ const eb = imb - ia; // b→a
kf = ef > 0 ? halfRho * ef * ef : 0;
kb = eb > 0 ? halfRho * eb * eb : 0;
// small contraction (vena contracta) loss entering a narrower node
- const cf = 1 / mb - ia;
- const cb = 1 / ma - ib;
+ const cf = imb - ia;
+ const cb = ima - ib;
if (cf > 0) kf += 0.1 * halfRho * cf * cf;
if (cb > 0) kb += 0.1 * halfRho * cb * cb;
} else {
@@ -719,19 +725,21 @@ export class AirwayNetwork {
// 4) walls (velocity at half step from p(n), displacement integrates)
const wallU = this.wallU;
+ const hasWall = this.hasWall, wallM = this.wallM, wallR = this.wallR, wallK = this.wallK;
+ const wallV = this.wallV, wallY = this.wallY, wallRad = this.wallRad;
let wallRadSum = 0;
for (let k = 0; k < N; k++) {
- if (!this.hasWall[k]) continue;
- const m = this.wallM[k];
- const r = this.wallR[k];
- const v = ((m * invT - 0.5 * r) * this.wallV[k] + p[k] - this.wallK[k] * this.wallY[k]) / (m * invT + 0.5 * r);
- this.wallV[k] = v;
- this.wallY[k] += T * v;
+ if (!hasWall[k]) continue;
+ const m = wallM[k];
+ const r = wallR[k];
+ const v = ((m * invT - 0.5 * r) * wallV[k] + p[k] - wallK[k] * wallY[k]) / (m * invT + 0.5 * r);
+ wallV[k] = v;
+ wallY[k] += T * v;
const a = area[k] > minA ? area[k] : minA;
const uw = this.wallPerim[k] * Math.sqrt(a) * dx[k] * v;
wallU[k] = uw;
flowSum[k] -= uw;
- wallRadSum += uw * this.wallRad[k];
+ wallRadSum += uw * wallRad[k];
}
// 5) nodes (radiation loads handled semi-implicitly)
diff --git a/src/engine/phonetics/english.ts b/src/engine/phonetics/english.ts
new file mode 100644
index 0000000..9ec5a9f
--- /dev/null
+++ b/src/engine/phonetics/english.ts
@@ -0,0 +1,233 @@
+/**
+ * English text → phoneme segments: CMUdict (ARPAbet with stress) when loaded, letter-to-sound
+ * rules otherwise; American flapping and dark /l/; numbers spelled out; punctuation → phrase
+ * breaks and intonation.
+ */
+import type { Segment } from "./planner.ts";
+
+const ARPA: Record<string, string> = {
+ AA: "ɑ", AE: "æ", AH: "ʌ", AO: "ɔ", AW: "aʊ", AY: "aɪ", EH: "ɛ", ER: "ɝ", EY: "eɪ", IH: "ɪ", IY: "i", OW: "oʊ", OY: "ɔɪ", UH: "ʊ", UW: "u",
+ B: "b", CH: "tʃ", D: "d", DH: "ð", F: "f", G: "g", HH: "h", JH: "dʒ", K: "k", L: "l", M: "m", N: "n", NG: "ŋ", P: "p", R: "ɹ", S: "s", SH: "ʃ", T: "t", TH: "θ", V: "v", W: "w", Y: "j", Z: "z", ZH: "ʒ",
+};
+const VOWELS = new Set(["ɑ", "æ", "ʌ", "ə", "ɔ", "aʊ", "aɪ", "ɛ", "ɝ", "ɚ", "eɪ", "ɪ", "i", "oʊ", "ɔɪ", "ʊ", "u"]);
+/** monosyllabic function words are unstressed in running speech (and reduce) */
+const FUNCTION_WORDS = new Set("a an the of to in on at by for from with as and or but nor so if is am are was were be been do does did has have had will would can could should shall may might must it its i you he she we they me him her us them my your his our their this that than then there not no".split(" "));
+const REDUCE: Record<string, string> = { ʌ: "ə", æ: "ə", ɑ: "ə", ɛ: "ə", ɔ: "ə", u: "ə", ʊ: "ə" };
+
+export interface Phrase {
+ segments: Segment[];
+ intonation: "statement" | "question";
+ /** pause after the phrase (s) */
+ pause: number;
+ words: string[];
+}
+
+export class EnglishG2P {
+ private dict: Map<string, string> | null = null;
+ private loading: Promise<void> | null = null;
+
+ get loaded(): boolean {
+ return !!this.dict;
+ }
+
+ /** Load the gzipped dictionary ("word\tPHONES" lines). Browser: fetch + DecompressionStream. */
+ load(url = "/data/cmudict.txt.gz"): Promise<void> {
+ if (this.dict) return Promise.resolve();
+ if (this.loading) return this.loading;
+ this.loading = (async () => {
+ try {
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`dictionary ${res.status}`);
+ const bytes = new Uint8Array(await res.arrayBuffer());
+ // servers differ: some send Content-Encoding: gzip (already inflated by the browser)
+ let text: string;
+ if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
+ text = await new Response(stream).text();
+ } else text = new TextDecoder().decode(bytes);
+ this.setDictionaryText(text);
+ } catch (e) {
+ this.loading = null; // allow a retry
+ throw e;
+ }
+ })();
+ return this.loading;
+ }
+
+ setDictionaryText(text: string): void {
+ const m = new Map<string, string>();
+ for (const line of text.split("\n")) {
+ const tab = line.indexOf("\t");
+ if (tab > 0) m.set(line.slice(0, tab), line.slice(tab + 1));
+ }
+ this.dict = m;
+ }
+
+ /** Text → phrases of segments. */
+ toPhrases(text: string): Phrase[] {
+ const phrases: Phrase[] = [];
+ const normalized = expandNumbers(text.replace(/[’']/g, "'"));
+ // split on phrase punctuation, keeping the delimiter
+ const parts = normalized.split(/([.!?;:,]+)/);
+ let words: string[] = [];
+ const flush = (delim: string) => {
+ if (!words.length) return;
+ const segs: Segment[] = [];
+ for (const w of words) {
+ const ws = this.word(w);
+ if (!ws.length) continue;
+ ws[ws.length - 1].wordEnd = true;
+ segs.push(...ws);
+ }
+ applyAllophones(segs);
+ const q = delim.includes("?");
+ const pause = /[.!?]/.test(delim) ? 0.35 : delim ? 0.18 : 0.3;
+ if (segs.length) phrases.push({ segments: segs, intonation: q ? "question" : "statement", pause, words });
+ words = [];
+ };
+ for (const part of parts) {
+ if (/^[.!?;:,]+$/.test(part)) flush(part);
+ else words.push(...part.toLowerCase().split(/[^a-z'\-]+/).filter(Boolean));
+ }
+ flush("");
+ return phrases;
+ }
+
+ /** One word → segments with lexical stress. */
+ word(w: string): Segment[] {
+ const clean = w.toLowerCase().replace(/^'+|'+$/g, "");
+ const entry = this.dict?.get(clean);
+ if (entry) {
+ const segs = arpabetToSegments(entry);
+ if (FUNCTION_WORDS.has(clean)) {
+ const nv = segs.filter((s) => VOWELS.has(s.ipa)).length;
+ for (const s of segs) {
+ s.stress = 0;
+ // short function words reduce toward schwa ("of" → əv, "and" → ənd), except /i ɪ eɪ aɪ oʊ/
+ if (nv === 1 && REDUCE[s.ipa] && !["you", "do", "to", "who", "not", "no"].includes(clean)) s.ipa = REDUCE[s.ipa];
+ }
+ }
+ return segs;
+ }
+ // hyphenated compounds
+ if (clean.includes("-")) return clean.split("-").flatMap((p) => this.word(p));
+ return letterToSound(clean);
+ }
+}
+
+export function arpabetToSegments(phones: string): Segment[] {
+ const out: Segment[] = [];
+ for (const ph of phones.trim().split(/\s+/)) {
+ const m = ph.match(/^([A-Z]+)([012])?$/);
+ if (!m) continue;
+ const base = m[1];
+ const stress = m[2] === "1" ? 1 : m[2] === "2" ? 2 : 0;
+ let ipa = ARPA[base];
+ if (!ipa) continue;
+ if (base === "AH" && stress === 0) ipa = "ə";
+ if (base === "ER" && stress === 0) ipa = "ɚ";
+ out.push({ ipa, stress: VOWELS.has(ipa) ? stress : 0 });
+ }
+ return out;
+}
+
+/** American English allophones: flapping and velarised coda /l/ (in place). */
+function applyAllophones(segs: Segment[]): void {
+ for (let i = 1; i < segs.length - 1; i++) {
+ const s = segs[i];
+ const prev = segs[i - 1], next = segs[i + 1];
+ const pv = VOWELS.has(prev.ipa) || prev.ipa === "ɹ";
+ const nv = VOWELS.has(next.ipa);
+ // /t d/ between a vowel and an unstressed vowel → tap ("water", "ladder", "got it")
+ if ((s.ipa === "t" || s.ipa === "d") && pv && nv && !next.stress) s.ipa = "ɾ";
+ }
+ for (let i = 0; i < segs.length; i++) {
+ const s = segs[i];
+ if (s.ipa !== "l") continue;
+ const next = segs[i + 1];
+ // coda /l/ (before a consonant, pause, or word end) is velarised
+ if (!next || !VOWELS.has(next.ipa) || s.wordEnd) s.ipa = "ɫ";
+ }
+}
+
+// ---------------------------------------------------------------- numbers
+const ONES = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
+const TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
+function numberWords(n: number): string {
+ if (n < 20) return ONES[n];
+ if (n < 100) return TENS[Math.floor(n / 10)] + (n % 10 ? " " + ONES[n % 10] : "");
+ if (n < 1000) return ONES[Math.floor(n / 100)] + " hundred" + (n % 100 ? " " + numberWords(n % 100) : "");
+ if (n < 1e6) return numberWords(Math.floor(n / 1000)) + " thousand" + (n % 1000 ? " " + numberWords(n % 1000) : "");
+ return n.toString().split("").map((d) => ONES[+d]).join(" ");
+}
+function expandNumbers(t: string): string {
+ return t.replace(/\d+/g, (d) => " " + numberWords(parseInt(d, 10)) + " ");
+}
+
+// ---------------------------------------------------------------- letter-to-sound fallback
+/**
+ * Compact rule set for words missing from the dictionary. Rules are tried longest-first at each
+ * position; context classes: '#' word boundary, 'V' vowel letter, 'C' consonant letter.
+ */
+type Rule = [pre: string, grapheme: string, post: string, phones: string];
+const RULES: Rule[] = [
+ ["", "tion", "", "ʃ ə n"], ["", "sion", "", "ʒ ə n"], ["", "ture", "", "tʃ ɚ"], ["", "ough", "#", "oʊ"], ["", "augh", "", "ɔ"],
+ ["", "igh", "", "aɪ"], ["", "eigh", "", "eɪ"], ["", "tch", "", "tʃ"], ["", "dge", "", "dʒ"], ["", "sch", "", "s k"],
+ ["", "ch", "", "tʃ"], ["", "sh", "", "ʃ"], ["", "th", "", "θ"], ["", "ph", "", "f"], ["", "wh", "", "w"], ["", "ck", "", "k"],
+ ["", "ng", "#", "ŋ"], ["", "ng", "", "ŋ g"], ["", "qu", "", "k w"], ["#", "kn", "", "n"], ["#", "wr", "", "ɹ"], ["", "gh", "", ""],
+ ["", "ee", "", "i"], ["", "ea", "", "i"], ["", "oo", "", "u"], ["", "ou", "", "aʊ"], ["", "ow", "#", "oʊ"], ["", "ow", "", "aʊ"],
+ ["", "oi", "", "ɔɪ"], ["", "oy", "", "ɔɪ"], ["", "ai", "", "eɪ"], ["", "ay", "", "eɪ"], ["", "au", "", "ɔ"], ["", "aw", "", "ɔ"],
+ ["", "ie", "#", "aɪ"], ["", "ie", "", "i"], ["", "ei", "", "eɪ"], ["", "ey", "#", "i"], ["", "oa", "", "oʊ"], ["", "ue", "#", "u"],
+ ["", "er", "#", "ɚ"], ["", "er", "C", "ɝ"], ["", "ir", "", "ɝ"], ["", "ur", "", "ɝ"], ["", "or", "", "ɔ ɹ"], ["", "ar", "", "ɑ ɹ"],
+ ["", "le", "#", "ə ɫ"], ["", "ed", "#", "d"], ["", "es", "#", "z"], ["C", "s", "#", "s"], ["V", "s", "#", "z"], ["", "y", "#", "i"],
+ ["#", "y", "", "j"], ["C", "y", "", "aɪ"], ["", "e", "#", ""],
+ ["", "a", "CV", "eɪ"], ["", "a", "", "æ"], ["", "e", "", "ɛ"], ["", "i", "CV", "aɪ"], ["", "i", "", "ɪ"], ["", "o", "CV", "oʊ"],
+ ["", "o", "", "ɑ"], ["", "u", "CV", "u"], ["", "u", "", "ʌ"], ["", "y", "", "ɪ"],
+ ["", "c", "e", "s"], ["", "c", "i", "s"], ["", "c", "y", "s"], ["", "c", "", "k"], ["", "g", "e", "dʒ"], ["", "g", "i", "dʒ"], ["", "g", "", "g"],
+ ["", "x", "", "k s"], ["", "j", "", "dʒ"], ["", "q", "", "k"], ["", "b", "", "b"], ["", "d", "", "d"], ["", "f", "", "f"], ["", "h", "", "h"],
+ ["", "k", "", "k"], ["", "l", "", "l"], ["", "m", "", "m"], ["", "n", "", "n"], ["", "p", "", "p"], ["", "r", "", "ɹ"], ["", "s", "", "s"],
+ ["", "t", "", "t"], ["", "v", "", "v"], ["", "w", "", "w"], ["", "z", "", "z"],
+];
+const isV = (ch: string | undefined) => !!ch && "aeiouy".includes(ch);
+function matchCtx(word: string, i: number, ctx: string, dir: 1 | -1): boolean {
+ if (!ctx) return true;
+ let pos = i;
+ for (let k = 0; k < ctx.length; k++) {
+ const c = dir === 1 ? ctx[k] : ctx[ctx.length - 1 - k];
+ const ch = word[pos];
+ if (c === "#") {
+ if (ch !== undefined) return false;
+ } else if (c === "V") {
+ if (!isV(ch)) return false;
+ } else if (c === "C") {
+ if (!ch || isV(ch)) return false;
+ } else if (ch !== c) return false;
+ pos += dir;
+ }
+ return true;
+}
+export function letterToSound(word: string): Segment[] {
+ const phones: string[] = [];
+ let i = 0;
+ while (i < word.length) {
+ let done = false;
+ for (const [pre, g, post, ph] of RULES) {
+ if (!word.startsWith(g, i)) continue;
+ if (!matchCtx(word, i - 1, pre, -1)) continue;
+ if (!matchCtx(word, i + g.length, post, 1)) continue;
+ if (ph) phones.push(...ph.split(" "));
+ i += g.length;
+ done = true;
+ break;
+ }
+ if (!done) i++;
+ }
+ // stress the first vowel (crude but serviceable)
+ let stressed = false;
+ return phones.map((ipa) => {
+ const v = VOWELS.has(ipa);
+ const seg: Segment = { ipa, stress: v && !stressed ? 1 : 0 };
+ if (v) stressed = true;
+ return seg;
+ });
+}
diff --git a/src/engine/phonetics/planner.ts b/src/engine/phonetics/planner.ts
index e6fc7f2..f10da5f 100644
--- a/src/engine/phonetics/planner.ts
+++ b/src/engine/phonetics/planner.ts
@@ -222,3 +222,20 @@ export function planUtterance(input: Segment[], o: PlanOptions): Plan {
});
return { gestures, segments: planned, end };
}
+
+/** 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 }[],
+ o: Omit<PlanOptions, "intonation">,
+): Plan {
+ const all: Plan = { gestures: [], segments: [], end: o.t0 };
+ let t = o.t0;
+ for (const p of phrases) {
+ const plan = planUtterance(p.segments, { ...o, t0: t, intonation: p.intonation ?? "statement" });
+ all.gestures.push(...plan.gestures);
+ all.segments.push(...plan.segments);
+ t = plan.end + (p.pause ?? 0.25);
+ all.end = plan.end;
+ }
+ return all;
+}
diff --git a/src/engine/sources/glottis.ts b/src/engine/sources/glottis.ts
index b00d017..1b382a8 100644
--- a/src/engine/sources/glottis.ts
+++ b/src/engine/sources/glottis.ts
@@ -76,6 +76,7 @@ export class ParametricGlottis {
private readonly drift: Drift;
private driftValue = 0;
private driftCounter = 0;
+ private pitchFactor = 1;
/** smoothed voicing gate 0..1 (telemetry) */
voicing = 0;
private voicingSm = 0;
@@ -98,7 +99,7 @@ export class ParametricGlottis {
constructor(fs: number) {
this.fs = fs;
- this.drift = new Drift(fs / 64, 0.3, 4242);
+ this.drift = new Drift(fs / 32, 0.3, 4242);
this.dpCoef = 1 - Math.exp(-TAU * 30 / fs);
this.voiceCoef = 1 - Math.exp(-TAU * 25 / fs);
this.smCoef = 1 - Math.exp(-1 / (0.004 * fs));
@@ -119,15 +120,16 @@ export class ParametricGlottis {
const P = this.params;
this.dpSm += this.dpCoef * (dp - this.dpSm);
- // slow drift updated at a decimated rate
+ // drift and vibrato evaluated at a decimated rate (pitch modulation is slow)
if (--this.driftCounter <= 0) {
- this.driftCounter = 64;
+ this.driftCounter = 32;
this.driftValue = this.drift.step();
+ this.vibPhase += ((P.vibratoRate * 32) / this.fs) * (1 + 0.04 * this.driftValue);
+ if (this.vibPhase > 1) this.vibPhase -= 1;
+ const cents = P.vibratoDepth * Math.sin(TAU * this.vibPhase) + P.drift * this.driftValue;
+ this.pitchFactor = Math.pow(2, cents / 1200);
}
- this.vibPhase += (P.vibratoRate / this.fs) * (1 + 0.04 * this.driftValue);
- if (this.vibPhase > 1) this.vibPhase -= 1;
- const cents = P.vibratoDepth * Math.sin(TAU * this.vibPhase) + P.drift * this.driftValue;
- let f0 = P.f0 * Math.pow(2, cents / 1200);
+ let f0 = P.f0 * this.pitchFactor;
// fry pulls the rate down toward ~45 Hz
if (P.fry > 0) f0 = f0 * (1 - P.fry) + Math.min(f0, 48) * P.fry;
this.f0Now = f0;
diff --git a/src/engine/voice/humanVoice.ts b/src/engine/voice/humanVoice.ts
index 9dcad4e..3d3da72 100644
--- a/src/engine/voice/humanVoice.ts
+++ b/src/engine/voice/humanVoice.ts
@@ -282,8 +282,9 @@ export class HumanVoice {
this.scoreF0 = null;
}
this.clock += dt;
- this.enforceContacts();
+ // contact constraint on the frame computed anyway; re-apply only if a correction was made
this.airway.apply(this.artic.x, dt);
+ if (this.enforceContacts()) this.airway.apply(this.artic.x, 0);
this.airway.net.beginBlock(this.ctrlEvery);
this.ctrlCounter = this.ctrlEvery;
// breath: fast attack, slower release; a speaking score breathes on its own
@@ -314,14 +315,15 @@ export class HumanVoice {
* inward velocity removed (inelastic). Keeps held closures still (no air pumping), makes
* releases start at the surface, and keeps the drawn anatomy physical.
*/
- private enforceContacts(): void {
+ private enforceContacts(): boolean {
const tract = this.airway.tract;
const x = this.artic.x, vel = this.artic.v;
- tract.compute(x);
const k = tract.scale;
+ let changed = false;
const lim = -this.maxPenetration * k;
const fix = (d: number, n: { x: number; y: number }, kx: "ttX" | "tbX", ky: "ttY" | "tbY") => {
if (!(d < lim)) return;
+ changed = true;
const depth = lim - d; // > 0, body cm
// body → template displacement (oral x is compressed by 0.86 in the template map)
const sx = (x[kx] > 0.5 ? 1 / 0.86 : 1) / k;
@@ -336,6 +338,7 @@ export class HumanVoice {
};
fix(tract.contactTip, tract.contactTipN, "ttX", "ttY");
fix(tract.contactBody, tract.contactBodyN, "tbX", "tbY");
+ return changed;
}
telemetry(): VoiceTelemetry {
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index c21fb05..7f55398 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -10,6 +10,8 @@ import { VoicePanel } from "./components/VoicePanel.tsx";
import { ArticPanel } from "./components/ArticPanel.tsx";
import { Keys } from "./components/Keys.tsx";
import { Segmented, Toggle } from "./components/Controls.tsx";
+import { SpeakPanel } from "./components/SpeakPanel.tsx";
+import type { Mode } from "./store.ts";
import type { BodyName } from "../worklet/protocol.ts";
function TopBar() {
@@ -20,6 +22,8 @@ function TopBar() {
const setBody = useStore((s) => s.setBody);
const volume = useStore((s) => s.volume);
const setVolume = useStore((s) => s.setVolume);
+ const mode = useStore((s) => s.mode);
+ const setMode = useStore((s) => s.setMode);
const [load, setLoad] = useState(0);
useEffect(() => {
const id = setInterval(() => setLoad(engine.latest?.load ?? 0), 500);
@@ -31,6 +35,15 @@ function TopBar() {
<span className="wordmark">Chimera</span>
<span className="tagline">A voice grown from a simulated airway</span>
</div>
+ <Segmented<Mode>
+ label="Mode"
+ value={mode}
+ onChange={setMode}
+ options={[
+ { value: "play", label: "Play" },
+ { value: "speak", label: "Speak" },
+ ]}
+ />
<Segmented<BodyName>
label="Body"
value={body}
@@ -98,6 +111,26 @@ function StartPrompt() {
);
}
+function Deck() {
+ const mode = useStore((s) => s.mode);
+ if (mode === "speak") return <SpeakPanel />;
+ return (
+ <>
+ <section className="deck">
+ <div className="panel vowel-panel">
+ <h2>Vowels</h2>
+ <VowelMap />
+ </div>
+ <VoicePanel />
+ <ArticPanel />
+ </section>
+ <footer className="keys-bar">
+ <Keys />
+ </footer>
+ </>
+ );
+}
+
export function App() {
return (
<div className="app">
@@ -123,17 +156,7 @@ export function App() {
</figure>
</aside>
</main>
- <section className="deck">
- <div className="panel vowel-panel">
- <h2>Vowels</h2>
- <VowelMap />
- </div>
- <VoicePanel />
- <ArticPanel />
- </section>
- <footer className="keys-bar">
- <Keys />
- </footer>
+ <Deck />
</div>
);
}
diff --git a/src/ui/components/ScoreView.tsx b/src/ui/components/ScoreView.tsx
new file mode 100644
index 0000000..338d269
--- /dev/null
+++ b/src/ui/components/ScoreView.tsx
@@ -0,0 +1,127 @@
+import { useEffect, useRef } from "react";
+import { useCanvasLoop, font } from "../useCanvas.ts";
+import { engine } from "../../audio/AudioEngine.ts";
+import { currentPlan, onPlan, type SpokenPlan } from "../speech.ts";
+import { activation, type Gesture } from "../../engine/control/score.ts";
+import { C } from "../colors.ts";
+
+const ROWS: { name: string; keys: string[] }[] = [
+ { name: "Lips", keys: ["lipAp", "lipProt", "lipWidth", "labiodental"] },
+ { name: "Tongue tip", keys: ["ttX", "ttY", "ttCurl", "lateral"] },
+ { name: "Tongue body", keys: ["tbX", "tbY", "root"] },
+ { name: "Soft palate", keys: ["velum"] },
+ { name: "Glottis", keys: ["abduction", "closure"] },
+];
+
+function rowOf(g: Gesture): number {
+ const keys = Object.keys(g.targets);
+ // vowel gestures touch body + lips; draw them on the body row
+ if (keys.includes("tbX") && keys.includes("lipAp") && keys.length > 4) return 2;
+ // tip-driven segments that also round the lips (/ɹ ʃ/) belong to the tongue-tip row
+ if (keys.includes("ttX") || keys.includes("ttCurl")) return 1;
+ for (let r = 0; r < ROWS.length; r++) if (keys.some((k) => ROWS[r].keys.includes(k))) return r;
+ return -1;
+}
+
+/** Gestural score of the current utterance (Articulatory Phonology), with live playhead. */
+export function ScoreView() {
+ const planRef = useRef<SpokenPlan | null>(currentPlan());
+ useEffect(() => onPlan((p) => (planRef.current = p)), []);
+ const ref = useCanvasLoop(({ ctx, w, h }) => {
+ ctx.clearRect(0, 0, w, h);
+ const sp = planRef.current;
+ const left = 92, right = w - 8, top = 8, bottom = h - 30;
+ const rowH = (bottom - top) / (ROWS.length + 1);
+ ctx.font = font(12);
+ ctx.fillStyle = C.textDim;
+ ROWS.forEach((r, i) => ctx.fillText(r.name, 4, top + rowH * (i + 0.62)));
+ ctx.fillText("Pitch", 4, top + rowH * (ROWS.length + 0.62));
+ ctx.strokeStyle = "rgba(255,255,255,0.06)";
+ for (let i = 0; i <= ROWS.length + 1; i++) {
+ ctx.beginPath();
+ ctx.moveTo(left, top + rowH * i);
+ ctx.lineTo(right, top + rowH * i);
+ ctx.stroke();
+ }
+ if (!sp) {
+ ctx.fillStyle = C.textDim;
+ ctx.fillText("Speak something to see its gestures: which articulator moves, when, and how they overlap.", left, h / 2);
+ return;
+ }
+ const plan = sp.plan;
+ const T0 = -0.05, T1 = plan.end + 0.15;
+ const X = (t: number) => left + ((t - T0) / (T1 - T0)) * (right - left);
+ const tele = engine.latest;
+ const now = sp.offset !== null && tele ? tele.t.clock - sp.offset : -1;
+ // gestures
+ const f0s: { t: number; f: number }[] = [];
+ for (const g of plan.gestures) {
+ if (g.targets.f0 !== undefined) {
+ f0s.push({ t: (g.t0 + g.t1) / 2, f: g.targets.f0 });
+ continue;
+ }
+ const r = rowOf(g);
+ if (r < 0) continue;
+ const x0 = X(g.t0 - g.rampIn), x1 = X(g.t1 + g.rampOut);
+ const xa = X(g.t0), xb = X(g.t1);
+ const y = top + rowH * r + rowH * 0.18, hh = rowH * 0.64;
+ const isVowel = r === 2 && Object.keys(g.targets).length > 4;
+ const active = now >= g.t0 - g.rampIn && now <= g.t1 + g.rampOut ? activation(g, now) : 0;
+ const base = isVowel ? "154,163,168" : "242,207,91";
+ const grad = ctx.createLinearGradient(x0, 0, x1, 0);
+ const a = isVowel ? 0.28 : 0.5;
+ grad.addColorStop(0, `rgba(${base},0)`);
+ grad.addColorStop(Math.max(0, Math.min(1, (xa - x0) / Math.max(1, x1 - x0))), `rgba(${base},${a})`);
+ grad.addColorStop(Math.max(0, Math.min(1, (xb - x0) / Math.max(1, x1 - x0))), `rgba(${base},${a})`);
+ grad.addColorStop(1, `rgba(${base},0)`);
+ ctx.fillStyle = grad;
+ ctx.beginPath();
+ ctx.roundRect(x0, y, Math.max(2, x1 - x0), hh, 4);
+ ctx.fill();
+ if (active > 0.05) {
+ ctx.strokeStyle = `rgba(${base},${0.5 + 0.5 * active})`;
+ ctx.lineWidth = 1.5;
+ ctx.stroke();
+ }
+ if (g.label && (xb - xa > 12 || !isVowel)) {
+ ctx.fillStyle = isVowel ? "rgba(232,234,235,0.85)" : "#1d1a10";
+ ctx.font = font(12, 600);
+ const lbl = g.label === "aspiration" || g.label === "voiceless" ? "open" : g.label === "velum" ? "lowered" : g.label;
+ ctx.fillText(lbl, Math.max(x0 + 3, xa + 2), y + hh * 0.7);
+ }
+ }
+ // pitch contour
+ if (f0s.length) {
+ f0s.sort((p, q) => p.t - q.t);
+ const fmin = Math.min(...f0s.map((p) => p.f)) * 0.9, fmax = Math.max(...f0s.map((p) => p.f)) * 1.1;
+ const yb = top + rowH * ROWS.length + rowH * 0.9, ya = top + rowH * ROWS.length + rowH * 0.1;
+ ctx.beginPath();
+ f0s.forEach((p, i) => {
+ const x = X(p.t), y = yb - ((p.f - fmin) / Math.max(1, fmax - fmin)) * (yb - ya);
+ if (i) ctx.lineTo(x, y);
+ else ctx.moveTo(x, y);
+ });
+ ctx.strokeStyle = "rgba(232,234,235,0.8)";
+ ctx.lineWidth = 1.5;
+ ctx.stroke();
+ }
+ // segment labels along the bottom
+ ctx.font = font(13, 500);
+ ctx.fillStyle = "rgba(232,234,235,0.9)";
+ for (const s of plan.segments) {
+ const x = X((s.t0 + s.t1) / 2);
+ const tw = ctx.measureText(s.ipa).width;
+ ctx.fillText(s.ipa, x - tw / 2, h - 10);
+ }
+ // playhead
+ if (now >= T0 && now <= T1) {
+ ctx.strokeStyle = C.caliper;
+ ctx.lineWidth = 1.5;
+ ctx.beginPath();
+ ctx.moveTo(X(now), top);
+ ctx.lineTo(X(now), h - 24);
+ ctx.stroke();
+ }
+ });
+ return <canvas ref={ref} className="score-canvas" aria-label="Gestural score of the current utterance" role="img" />;
+}
diff --git a/src/ui/components/SpeakPanel.tsx b/src/ui/components/SpeakPanel.tsx
new file mode 100644
index 0000000..80396a9
--- /dev/null
+++ b/src/ui/components/SpeakPanel.tsx
@@ -0,0 +1,131 @@
+import { useEffect, useState } from "react";
+import { useStore } from "../store.ts";
+import { speakText, speakPhrases, stopSpeaking, onPlan, currentPlan } from "../speech.ts";
+import { tokenizeIpa } from "../../engine/phonetics/ipa.ts";
+import { Slider, Toggle } from "./Controls.tsx";
+import { ScoreView } from "./ScoreView.tsx";
+
+const EXAMPLES = ["Hello. Can you hear me?", "She sells sea shells by the sea shore.", "Every sound here is air moving through a throat.", "The quick brown fox jumps over the lazy dog."];
+
+// IPA pulmonic consonant chart (rows = manner, columns = place); empty cells are null
+const PLACES = ["Bilabial", "Labiodental", "Dental", "Alveolar", "Postalveolar", "Retroflex", "Palatal", "Velar", "Uvular", "Pharyngeal", "Glottal"];
+const CHART: [string, (string | null)[][]][] = [
+ ["Plosive", [["p", "b"], [null, null], [null, null], ["t", "d"], [null, null], ["ʈ", "ɖ"], ["c", "ɟ"], ["k", "g"], ["q", "ɢ"], [null, null], ["ʔ", null]]],
+ ["Nasal", [[null, "m"], [null, "ɱ"], [null, null], [null, "n"], [null, null], [null, "ɳ"], [null, "ɲ"], [null, "ŋ"], [null, "ɴ"], [null, null], [null, null]]],
+ ["Trill", [[null, "ʙ"], [null, null], [null, null], [null, "r"], [null, null], [null, null], [null, null], [null, null], [null, "ʀ"], [null, null], [null, null]]],
+ ["Tap", [[null, null], [null, null], [null, null], [null, "ɾ"], [null, null], [null, "ɽ"], [null, null], [null, null], [null, null], [null, null], [null, null]]],
+ ["Fricative", [["ɸ", "β"], ["f", "v"], ["θ", "ð"], ["s", "z"], ["ʃ", "ʒ"], ["ʂ", "ʐ"], ["ç", "ʝ"], ["x", "ɣ"], ["χ", "ʁ"], ["ħ", "ʕ"], ["h", "ɦ"]]],
+ ["Lateral fricative", [[null, null], [null, null], [null, null], ["ɬ", "ɮ"], [null, null], [null, null], [null, null], [null, null], [null, null], [null, null], [null, null]]],
+ ["Approximant", [[null, null], [null, "ʋ"], [null, null], [null, "ɹ"], [null, null], [null, "ɻ"], [null, "j"], [null, "ɰ"], [null, null], [null, null], [null, null]]],
+ ["Lateral", [[null, null], [null, null], [null, null], [null, "l"], [null, null], [null, "ɭ"], [null, "ʎ"], [null, null], [null, null], [null, null], [null, null]]],
+];
+
+export function SpeakPanel() {
+ const body = useStore((s) => s.body);
+ const f0 = useStore((s) => s.source.f0);
+ const start = useStore((s) => s.start);
+ const [text, setText] = useState(EXAMPLES[0]);
+ const [ipa, setIpa] = useState(false);
+ const [rate, setRate] = useState(1);
+ const [busy, setBusy] = useState(false);
+ const [trans, setTrans] = useState(currentPlan()?.transcription ?? "");
+ const [vowel, setVowel] = useState("ɑ");
+ useEffect(() => onPlan((p) => setTrans(p?.transcription ?? "")), []);
+
+ const speak = async () => {
+ setBusy(true);
+ try {
+ await start();
+ await speakText(text, { ipa, body, rate, f0 });
+ } finally {
+ setBusy(false);
+ }
+ };
+ const pad = async (c: string) => {
+ await start();
+ speakPhrases([{ segments: tokenizeIpa(`ˈ${vowel}${c}${vowel}`), intonation: "flat" }], { body, rate, f0 });
+ };
+
+ return (
+ <div className="speak">
+ <div className="panel speak-input">
+ <h2>Say something</h2>
+ <textarea
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) void speak();
+ e.stopPropagation();
+ }}
+ rows={3}
+ spellCheck={!ipa}
+ aria-label={ipa ? "IPA to speak" : "Text to speak"}
+ placeholder={ipa ? "Type IPA, for example ˈhɛloʊ" : "Type something for the voice to say"}
+ />
+ <div className="examples">
+ {EXAMPLES.map((ex) => (
+ <button key={ex} className="chip" onClick={() => { setText(ex); setIpa(false); }}>
+ {ex}
+ </button>
+ ))}
+ </div>
+ <div className="row">
+ <button className="primary" onClick={() => void speak()} disabled={busy}>
+ {busy ? "Preparing…" : "Speak"}
+ </button>
+ <button className="ghost" onClick={stopSpeaking}>Stop</button>
+ <Toggle label="Text is IPA" checked={ipa} onChange={setIpa} />
+ </div>
+ <Slider label="Speaking rate" value={rate} min={0.5} max={1.8} onChange={setRate} format={(v) => `${v.toFixed(2)}×`} />
+ <p className="transcription" aria-live="polite">{trans ? `/${trans}/` : "The transcription appears here."}</p>
+ </div>
+ <div className="panel chart-panel">
+ <h2>Consonants, between two vowels</h2>
+ <div className="chart-scroll">
+ <table className="ipa-chart">
+ <thead>
+ <tr>
+ <th />
+ {PLACES.map((p) => (
+ <th key={p} scope="col">{p}</th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {CHART.map(([manner, cells]) => (
+ <tr key={manner}>
+ <th scope="row">{manner}</th>
+ {cells.map((pair, i) => (
+ <td key={i}>
+ {pair.map((sym, j) =>
+ sym ? (
+ <button key={j} className="ipa" onClick={() => void pad(sym)} title={`Say ${vowel}${sym}${vowel}`}>
+ {sym}
+ </button>
+ ) : (
+ <span key={j} className="ipa-empty" />
+ ),
+ )}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ <div className="row">
+ <span className="dim">Vowel around it</span>
+ {["ɑ", "i", "u", "ə"].map((v) => (
+ <button key={v} className={`chip${vowel === v ? " on" : ""}`} onClick={() => setVowel(v)}>
+ {v}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="panel score-panel">
+ <h2>Gestural score</h2>
+ <ScoreView />
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/speech.ts b/src/ui/speech.ts
new file mode 100644
index 0000000..7614adf
--- /dev/null
+++ b/src/ui/speech.ts
@@ -0,0 +1,74 @@
+/** Main-thread speech planning: text/IPA → phrases → gestural plan → worklet. */
+import { EnglishG2P, type Phrase } from "../engine/phonetics/english.ts";
+import { tokenizeIpa } from "../engine/phonetics/ipa.ts";
+import { planPhrases, type Plan, type Segment } from "../engine/phonetics/planner.ts";
+import { engine } from "../audio/AudioEngine.ts";
+import type { Gesture } from "../engine/control/score.ts";
+
+export const g2p = new EnglishG2P();
+
+export interface SpokenPlan {
+ plan: Plan;
+ /** worklet-clock offset of the plan's time 0 (set when the worklet confirms) */
+ offset: number | null;
+ id: number;
+ transcription: string;
+}
+
+let current: SpokenPlan | null = null;
+const listeners = new Set<(p: SpokenPlan | null) => void>();
+engine.onPlanned((m) => {
+ if (current && m.id === current.id) {
+ current = { ...current, offset: m.t0 };
+ for (const l of listeners) l(current);
+ }
+});
+
+export function onPlan(l: (p: SpokenPlan | null) => void): () => void {
+ listeners.add(l);
+ return () => listeners.delete(l);
+}
+
+export function currentPlan(): SpokenPlan | null {
+ return current;
+}
+
+export function ipaToPhrases(text: string): Phrase[] {
+ return text
+ .split(/[|.?!]+/)
+ .map((p) => p.trim())
+ .filter(Boolean)
+ .map((p) => ({ segments: tokenizeIpa(p), intonation: "statement" as const, pause: 0.3, words: [] }));
+}
+
+export function transcribe(phrases: { segments: Segment[]; intonation?: string }[]): string {
+ return phrases.map((p) => p.segments.map((s) => (s.stress === 1 ? "ˈ" : s.stress === 2 ? "ˌ" : "") + s.ipa + (s.wordEnd ? " " : "")).join("").trim() + (p.intonation === "question" ? "?" : "")).join(" | ");
+}
+
+export function speakPhrases(phrases: { segments: Segment[]; intonation?: "statement" | "question" | "flat"; pause?: number }[], o: { body: string; rate: number; f0: number }): SpokenPlan {
+ const plan = planPhrases(phrases, { body: o.body, t0: 0, rate: o.rate, f0: o.f0 });
+ const id = engine.schedule({ gestures: plan.gestures.map((g: Gesture) => ({ ...g, targets: { ...g.targets } })), segments: plan.segments, end: plan.end });
+ current = { plan, offset: null, id, transcription: transcribe(phrases) };
+ for (const l of listeners) l(current);
+ return current;
+}
+
+export async function speakText(text: string, o: { ipa: boolean; body: string; rate: number; f0: number }): Promise<SpokenPlan | null> {
+ if (!text.trim()) return null;
+ let phrases: Phrase[];
+ if (o.ipa) phrases = ipaToPhrases(text);
+ else {
+ try {
+ await g2p.load();
+ } catch {
+ // dictionary unavailable: the letter-to-sound rules still work
+ }
+ phrases = g2p.toPhrases(text);
+ }
+ if (!phrases.length) return null;
+ return speakPhrases(phrases, o);
+}
+
+export function stopSpeaking(): void {
+ engine.stopSpeech();
+}
diff --git a/src/ui/store.ts b/src/ui/store.ts
index f229f23..7c758c2 100644
--- a/src/ui/store.ts
+++ b/src/ui/store.ts
@@ -6,6 +6,8 @@ import type { BodyName } from "../worklet/protocol.ts";
export const DEFAULT_F0: Record<BodyName, number> = { male: 110, female: 205, child: 260 };
+export type Mode = "play" | "speak";
+
export interface ViewOptions {
pressure: boolean;
particles: boolean;
@@ -26,6 +28,8 @@ interface State {
hold: boolean;
heldNotes: number[];
view: ViewOptions;
+ mode: Mode;
+ setMode: (m: Mode) => void;
start: () => Promise<void>;
setBody: (b: BodyName) => void;
setSource: (v: Partial<VoiceSource>) => void;
@@ -58,6 +62,8 @@ export const useStore = create<State>((set, get) => ({
hold: false,
heldNotes: [],
view: { pressure: true, particles: true, grid: false, calipers: true },
+ mode: "play",
+ setMode: (m) => set({ mode: m }),
start: async () => {
if (get().started || get().starting) return;
set({ starting: true, startError: null });
diff --git a/src/ui/styles.css b/src/ui/styles.css
index b6e9174..d64415a 100644
--- a/src/ui/styles.css
+++ b/src/ui/styles.css
@@ -406,6 +406,151 @@ input[type="range"]::-moz-range-thumb {
margin: 0;
}
+/* ---------- speak */
+.speak {
+ display: grid;
+ grid-template-columns: minmax(280px, 1fr) minmax(420px, 1.6fr);
+ grid-template-rows: auto auto;
+ gap: 10px;
+}
+
+.speak-input {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.speak-input textarea {
+ width: 100%;
+ resize: vertical;
+ min-height: 72px;
+ 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;
+}
+
+.examples {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.chip {
+ border: 1px solid var(--line);
+ background: transparent;
+ border-radius: 999px;
+ padding: 3px 10px;
+ font-size: 13px;
+ font-stretch: 87%;
+ color: var(--text-dim);
+ cursor: pointer;
+}
+
+.chip:hover,
+.chip.on {
+ color: var(--text);
+ border-color: var(--text-dim);
+}
+
+button.ghost {
+ background: transparent;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-s);
+ padding: 7px 14px;
+ cursor: pointer;
+}
+
+.transcription {
+ margin: 0;
+ font-size: 17px;
+ color: var(--text);
+ word-break: break-word;
+ min-height: 1.4em;
+}
+
+.dim {
+ color: var(--text-dim);
+ font-size: 13px;
+ font-stretch: 87%;
+}
+
+.chart-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ min-width: 0;
+}
+
+.chart-scroll {
+ overflow-x: auto;
+}
+
+.ipa-chart {
+ border-collapse: collapse;
+ font-size: 12px;
+ font-stretch: 87%;
+}
+
+.ipa-chart th {
+ color: var(--text-dim);
+ font-weight: 500;
+ padding: 2px 4px;
+ text-align: left;
+ white-space: nowrap;
+}
+
+.ipa-chart thead th {
+ font-size: 11px;
+ text-align: center;
+}
+
+.ipa-chart td {
+ border: 1px solid var(--line);
+ padding: 1px;
+ text-align: center;
+ white-space: nowrap;
+}
+
+.ipa-chart button.ipa,
+.ipa-empty {
+ display: inline-block;
+ width: 26px;
+ height: 26px;
+ vertical-align: middle;
+}
+
+.ipa-chart button.ipa {
+ border: 0;
+ border-radius: 3px;
+ background: transparent;
+ font-size: 17px;
+ font-stretch: 100%;
+ cursor: pointer;
+ font-family: var(--font);
+}
+
+.ipa-chart button.ipa:hover {
+ background: var(--caliper);
+ color: #1d1a10;
+}
+
+.score-panel {
+ grid-column: 1 / -1;
+ display: grid;
+ grid-template-rows: auto minmax(0, 1fr);
+}
+
+.score-canvas {
+ width: 100%;
+ height: 210px;
+ display: block;
+}
+
/* ---------- keys */
.keys-bar {
background: var(--inset);
@@ -480,6 +625,12 @@ input[type="range"]::-moz-range-thumb {
}
}
+@media (max-width: 900px) {
+ .speak {
+ grid-template-columns: 1fr;
+ }
+}
+
@media (max-width: 720px) {
.app {
padding: 8px;
diff --git a/src/worklet/processor.ts b/src/worklet/processor.ts
index 32d3290..9124289 100644
--- a/src/worklet/processor.ts
+++ b/src/worklet/processor.ts
@@ -59,6 +59,22 @@ class ChimeraProcessor extends AudioWorkletProcessor {
case "telemetry":
this.telemetryOn = m.enabled;
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 gs = m.gestures.slice(0, 4000);
+ for (const g of gs) {
+ g.t0 += off;
+ g.t1 += off;
+ }
+ 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 })) });
+ break;
+ }
+ case "stopSpeech":
+ this.voice.cancelScore();
+ break;
}
}
diff --git a/src/worklet/protocol.ts b/src/worklet/protocol.ts
index 5d02244..82f800e 100644
--- a/src/worklet/protocol.ts
+++ b/src/worklet/protocol.ts
@@ -1,6 +1,14 @@
/** Messages between the main thread and the CHIMERA AudioWorklet. */
import type { HumanArtic } from "../engine/anatomy/human.ts";
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";
+
+export interface PhraseMsg {
+ segments: Segment[];
+ intonation?: "statement" | "question" | "flat";
+ pause?: number;
+}
export type BodyName = "male" | "female" | "child";
@@ -9,7 +17,10 @@ export type ToWorklet =
| { type: "artic"; values: Partial<HumanArtic>; tipFree?: boolean }
| { type: "source"; values: Partial<VoiceSource> }
| { type: "gate"; level: number }
- | { type: "telemetry"; enabled: boolean };
+ | { 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: "stopSpeech" };
export interface TelemetryMessage {
type: "telemetry";
@@ -21,4 +32,12 @@ export interface TelemetryMessage {
nOr: number;
}
-export type FromWorklet = { type: "ready"; sampleRate: number; body: BodyName; nPh: number; nOr: number } | TelemetryMessage | { type: "error"; message: string };
+export interface PlannedMessage {
+ type: "planned";
+ id: number;
+ t0: number;
+ end: number;
+ segments: PlannedSegment[];
+}
+
+export type FromWorklet = { type: "ready"; sampleRate: number; body: BodyName; nPh: number; nOr: number } | TelemetryMessage | PlannedMessage | { type: "error"; message: string };
diff --git a/tests/english.test.ts b/tests/english.test.ts
new file mode 100644
index 0000000..e4a6d19
--- /dev/null
+++ b/tests/english.test.ts
@@ -0,0 +1,29 @@
+import { test, expect } from "bun:test";
+import { gunzipSync } from "node:zlib";
+import { readFileSync } from "node:fs";
+import { EnglishG2P, letterToSound } from "../src/engine/phonetics/english.ts";
+
+const g2p = new EnglishG2P();
+g2p.setDictionaryText(gunzipSync(readFileSync("public/data/cmudict.txt.gz")).toString("utf8"));
+const ipa = (s: { ipa: string }[]) => s.map((x) => x.ipa).join("");
+
+test("dictionary words with stress and allophones", () => {
+ const [p] = g2p.toPhrases("Hello world");
+ expect(ipa(p.segments)).toBe("həloʊwɝɫd");
+ expect(p.segments.find((s) => s.ipa === "oʊ")?.stress).toBe(1);
+ const [w] = g2p.toPhrases("water");
+ expect(ipa(w.segments)).toBe("wɔɾɚ");
+});
+
+test("punctuation makes phrases and question intonation", () => {
+ const ph = g2p.toPhrases("Is it on? Yes, it is.");
+ expect(ph.length).toBe(3);
+ expect(ph[0].intonation).toBe("question");
+ expect(ph[2].intonation).toBe("statement");
+});
+
+test("numbers are spelled out and unknown words fall back to rules", () => {
+ const [p] = g2p.toPhrases("42");
+ expect(p.words).toEqual(["forty", "two"]);
+ expect(ipa(letterToSound("zorblat")).length).toBeGreaterThan(4);
+});
diff --git a/tools/e2e.ts b/tools/e2e.ts
index 03aea17..1a041fb 100644
--- a/tools/e2e.ts
+++ b/tools/e2e.ts
@@ -55,6 +55,17 @@ async function run(viewport: { width: number; height: number }, tag: string) {
await page.keyboard.up("d");
const loadText = await page.locator(".load").textContent().catch(() => null);
logs.push(`[${tag}] load: ${loadText}`);
+ // speak mode
+ await page.getByRole("radio", { name: "Speak" }).click();
+ await page.waitForTimeout(200);
+ await page.getByRole("button", { name: /^Speak$/ }).click();
+ await page.waitForTimeout(1500);
+ await page.screenshot({ path: `${outDir}/${tag}-3-speak.png`, fullPage: true });
+ const trans = await page.locator(".transcription").textContent();
+ logs.push(`[${tag}] transcription: ${trans}`);
+ await page.locator("button.ipa", { hasText: "ʃ" }).first().click();
+ await page.waitForTimeout(700);
+ await page.screenshot({ path: `${outDir}/${tag}-4-pad.png` });
await page.close();
}
@@ -62,4 +73,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/i.test(l)).slice(0, 20).join("\n"));
+console.log(logs.filter((l) => /load|warn|transcription/i.test(l)).slice(0, 20).join("\n"));
diff --git a/tools/render-text.ts b/tools/render-text.ts
new file mode 100644
index 0000000..83e5342
--- /dev/null
+++ b/tools/render-text.ts
@@ -0,0 +1,34 @@
+/**
+ * English text → speech through the full pipeline. Usage: bun tools/render-text.ts out/name "Text." [male|female|child]
+ */
+import { gunzipSync } from "node:zlib";
+import { readFileSync } 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 { planPhrases } from "../src/engine/phonetics/planner.ts";
+import { EnglishG2P } from "../src/engine/phonetics/english.ts";
+import { writeWav } from "./lib/wav.ts";
+import { renderSpectrogram } from "./lib/spectrogram.ts";
+
+const name = process.argv[2] ?? "out/text";
+const text = process.argv[3] ?? "Hello world.";
+const bodyName = (process.argv[4] ?? "male") as "male" | "female" | "child";
+const body = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD }[bodyName];
+const f0 = { male: 112, female: 205, child: 250 }[bodyName];
+const g2p = new EnglishG2P();
+g2p.setDictionaryText(gunzipSync(readFileSync("public/data/cmudict.txt.gz")).toString("utf8"));
+const phrases = g2p.toPhrases(text);
+console.log(phrases.map((p) => p.segments.map((s) => (s.stress === 1 ? "ˈ" : "") + s.ipa).join("") + (p.intonation === "question" ? "?" : "")).join(" | "));
+const FS = 48000;
+const voice = new HumanVoice({ fsOut: FS, body });
+voice.setSource({ f0 });
+const plan = planPhrases(phrases, { body: bodyName, t0: 0.05, f0 });
+voice.schedule(plan.gestures);
+const total = Math.round(FS * (plan.end + 0.3));
+const out = new Float32Array(total);
+const t0 = performance.now();
+for (let i = 0; i < total; i += 128) voice.render(out, i, Math.min(128, total - i));
+const ms = performance.now() - t0;
+writeWav(`${name}.wav`, [out], FS);
+renderSpectrogram(`${name}.png`, out, FS, { title: text.toUpperCase().replace(/[^\x20-\x7e]/g, "?").slice(0, 120), maxFreq: 8000, windowMs: 5, marks: plan.segments.map((s) => ({ t: s.t0, label: "" })) });
+console.log(`wrote ${name}.wav ${(total / FS).toFixed(2)} s, rendered in ${ms.toFixed(0)} ms`);