mumble v1, needs tweaking and more vowels
This commit is contained in:
@@ -20,7 +20,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { parseMessage } from "./chatter-parser.ts";
|
import { parseMessage } from "./chatter-parser.ts";
|
||||||
import type { BubbleRenderData, ChatterSlot, Layout, LayoutItem, ParsedMessage } from "./chatter-types.ts";
|
import type { BubbleRenderData, ChatterSlot, Layout, LayoutItem, ParsedMessage, VoiceConfig } from "./chatter-types.ts";
|
||||||
|
import type { Mumble } from "./mumble";
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ */
|
/* ------------------------------------------------------------------ */
|
||||||
/* Config */
|
/* Config */
|
||||||
@@ -32,6 +33,8 @@ export interface ChatterOverlayConfig {
|
|||||||
* offscreen canvas.
|
* offscreen canvas.
|
||||||
*/
|
*/
|
||||||
measure?: (text: string, font: string) => number;
|
measure?: (text: string, font: string) => number;
|
||||||
|
mumble?: Mumble;
|
||||||
|
voice?: VoiceConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ */
|
/* ------------------------------------------------------------------ */
|
||||||
@@ -78,6 +81,8 @@ interface RuntimeState {
|
|||||||
|
|
||||||
export class ChatterOverlay {
|
export class ChatterOverlay {
|
||||||
private readonly measure: (text: string, font: string) => number;
|
private readonly measure: (text: string, font: string) => number;
|
||||||
|
private readonly mumble: Mumble | null;
|
||||||
|
private readonly voice: VoiceConfig | undefined;
|
||||||
private readonly configs = new Map<string, ChatterSlot>();
|
private readonly configs = new Map<string, ChatterSlot>();
|
||||||
private readonly runtimes = new Map<string, RuntimeState>();
|
private readonly runtimes = new Map<string, RuntimeState>();
|
||||||
private readonly icons = new Map<string, CanvasImageSource>();
|
private readonly icons = new Map<string, CanvasImageSource>();
|
||||||
@@ -85,6 +90,8 @@ export class ChatterOverlay {
|
|||||||
|
|
||||||
constructor(cfg: ChatterOverlayConfig = {}) {
|
constructor(cfg: ChatterOverlayConfig = {}) {
|
||||||
this.measure = cfg.measure ?? ((text, font) => this.measureWithCanvas(text, font));
|
this.measure = cfg.measure ?? ((text, font) => this.measureWithCanvas(text, font));
|
||||||
|
this.mumble = cfg.mumble ?? null;
|
||||||
|
this.voice = cfg.voice;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* -------------------------------------------------------------- */
|
/* -------------------------------------------------------------- */
|
||||||
@@ -146,6 +153,7 @@ export class ChatterOverlay {
|
|||||||
/** Force-clear the current bubble and all queued messages. */
|
/** Force-clear the current bubble and all queued messages. */
|
||||||
clear(entityId: string): void {
|
clear(entityId: string): void {
|
||||||
this.runtimes.delete(entityId);
|
this.runtimes.delete(entityId);
|
||||||
|
this.mumble?.stop(entityId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Skip the typewriter effect — instantly complete the current text. */
|
/** Skip the typewriter effect — instantly complete the current text. */
|
||||||
@@ -155,6 +163,7 @@ export class ChatterOverlay {
|
|||||||
if (rt.typingComplete) return;
|
if (rt.typingComplete) return;
|
||||||
rt.textElapsed = rt.parsed.totalDuration;
|
rt.textElapsed = rt.parsed.totalDuration;
|
||||||
rt.typingComplete = true;
|
rt.typingComplete = true;
|
||||||
|
this.mumble?.stop(entityId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Dismiss the current bubble. If queued messages remain, plays the next. */
|
/** Dismiss the current bubble. If queued messages remain, plays the next. */
|
||||||
@@ -163,6 +172,7 @@ export class ChatterOverlay {
|
|||||||
if (!rt) return;
|
if (!rt) return;
|
||||||
rt.dismissing = true;
|
rt.dismissing = true;
|
||||||
rt.dismissElapsed = 0;
|
rt.dismissElapsed = 0;
|
||||||
|
this.mumble?.stop(entityId);
|
||||||
}
|
}
|
||||||
|
|
||||||
isActive(entityId: string): boolean {
|
isActive(entityId: string): boolean {
|
||||||
@@ -274,6 +284,11 @@ export class ChatterOverlay {
|
|||||||
const totalDuration =
|
const totalDuration =
|
||||||
explicitDuration !== undefined && explicitDuration !== "auto" ? explicitDuration : autoDuration;
|
explicitDuration !== undefined && explicitDuration !== "auto" ? explicitDuration : autoDuration;
|
||||||
|
|
||||||
|
if (this.mumble !== null) {
|
||||||
|
const voice = config.voice ?? this.voice;
|
||||||
|
this.mumble.speak(entityId, parsed, voice);
|
||||||
|
}
|
||||||
|
|
||||||
const state: RuntimeState = {
|
const state: RuntimeState = {
|
||||||
parsed,
|
parsed,
|
||||||
layout,
|
layout,
|
||||||
@@ -305,6 +320,7 @@ export class ChatterOverlay {
|
|||||||
this.startNewMessage(entityId, next.text, rt.config);
|
this.startNewMessage(entityId, next.text, rt.config);
|
||||||
} else {
|
} else {
|
||||||
this.runtimes.delete(entityId);
|
this.runtimes.delete(entityId);
|
||||||
|
this.mumble?.stop(entityId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -217,10 +217,46 @@ export interface TimingConfig {
|
|||||||
holdLast?: number;
|
holdLast?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Voice */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export interface EmotionConfig {
|
||||||
|
/** Pitch multiplier on top of base pitch. */
|
||||||
|
pitch: number;
|
||||||
|
/** Additional noise mix added to base. E.g. whisper = 0.35. */
|
||||||
|
noiseBonus?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ContourConfig {
|
||||||
|
/** Pitch multiplier at the start of the sentence. */
|
||||||
|
from: number;
|
||||||
|
/** Pitch multiplier at the end of the sentence. */
|
||||||
|
to: number;
|
||||||
|
/** Easing shape. Default 'linear'. */
|
||||||
|
ease?: "linear" | "ease-in" | "ease-out" | "ease-in-out";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VoiceConfig {
|
||||||
|
/** Multiplier over 200 Hz reference. Default 1.0. */
|
||||||
|
basePitch?: number;
|
||||||
|
/** Multiplier on formant frequencies. Default 1.0. */
|
||||||
|
formantScale?: number;
|
||||||
|
/** Baseline breathiness, 0–1. Default 0.05. */
|
||||||
|
noiseMix?: number;
|
||||||
|
/** Per-burst volume, 0–1. Default 0.5. */
|
||||||
|
volume?: number;
|
||||||
|
/** Per-emotion overrides. Merged with defaults. */
|
||||||
|
emotions?: Partial<Record<VoiceMood, EmotionConfig>>;
|
||||||
|
/** Per-sentence-type contour overrides. Merged with defaults. */
|
||||||
|
contours?: Partial<Record<SentenceType, ContourConfig>>;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ChatterSlot {
|
export interface ChatterSlot {
|
||||||
bubble: BubbleConfig;
|
bubble: BubbleConfig;
|
||||||
text: TextConfig;
|
text: TextConfig;
|
||||||
timing?: TimingConfig;
|
timing?: TimingConfig;
|
||||||
|
voice?: VoiceConfig;
|
||||||
/** What to do when a new message arrives while one is active. Default 'queue'. */
|
/** What to do when a new message arrives while one is active. Default 'queue'. */
|
||||||
interrupt?: "queue" | "replace" | "reject";
|
interrupt?: "queue" | "replace" | "reject";
|
||||||
/** Priority for the queue. Higher = earlier. Default 0. */
|
/** Priority for the queue. Higher = earlier. Default 0. */
|
||||||
@@ -257,3 +293,32 @@ export interface ParseOptions {
|
|||||||
/** Default text color. Default '#000'. */
|
/** Default text color. Default '#000'. */
|
||||||
color?: string;
|
color?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_VOICE = {
|
||||||
|
basePitch: 1.0,
|
||||||
|
formantScale: 1.0,
|
||||||
|
noiseMix: 0.05,
|
||||||
|
volume: 0.5,
|
||||||
|
emotions: {
|
||||||
|
angry: { pitch: 1.15 },
|
||||||
|
sleepy: { pitch: 0.85 },
|
||||||
|
happy: { pitch: 1.1 },
|
||||||
|
sad: { pitch: 0.9 },
|
||||||
|
whisper: { pitch: 0.95, noiseBonus: 0.35 },
|
||||||
|
} as Record<VoiceMood, EmotionConfig>,
|
||||||
|
contours: {
|
||||||
|
statement: { from: 1.05, to: 0.95, ease: "linear" },
|
||||||
|
question: { from: 1.0, to: 1.2, ease: "ease-in" },
|
||||||
|
exclamation: { from: 1.25, to: 1.05, ease: "linear" },
|
||||||
|
ellipsis: { from: 1.3, to: 0.7, ease: "ease-out" },
|
||||||
|
fragment: { from: 1.0, to: 1.0, ease: "linear" },
|
||||||
|
} as Record<SentenceType, ContourConfig>,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const VOWEL_FORMANTS: Record<Vowel, { f1: number; f2: number; f3: number }> = {
|
||||||
|
a: { f1: 730, f2: 1090, f3: 2440 },
|
||||||
|
e: { f1: 530, f2: 1840, f3: 2480 },
|
||||||
|
i: { f1: 270, f2: 2290, f3: 3010 },
|
||||||
|
o: { f1: 570, f2: 840, f3: 2410 },
|
||||||
|
u: { f1: 300, f2: 870, f3: 2240 },
|
||||||
|
};
|
||||||
|
|||||||
@@ -99,3 +99,9 @@ export { parseMessage } from "./chatter-parser.ts";
|
|||||||
|
|
||||||
export { ChatterOverlay } from "./chatter-overlay.ts";
|
export { ChatterOverlay } from "./chatter-overlay.ts";
|
||||||
export type { ChatterOverlayConfig } from "./chatter-overlay.ts";
|
export type { ChatterOverlayConfig } from "./chatter-overlay.ts";
|
||||||
|
|
||||||
|
export { DEFAULT_VOICE, VOWEL_FORMANTS } from "./chatter-types.ts";
|
||||||
|
export type { ContourConfig, EmotionConfig, VoiceConfig } from "./chatter-types.ts";
|
||||||
|
|
||||||
|
export { Mumble, planMumble, synthesizeVowel } from "./mumble.ts";
|
||||||
|
export type { MumbleOptions, PlanMumbleOptions, ScheduledBurst } from "./mumble.ts";
|
||||||
|
|||||||
@@ -0,0 +1,537 @@
|
|||||||
|
/**
|
||||||
|
* mumble.ts — procedural speech synthesis for chatter.
|
||||||
|
*
|
||||||
|
* Synthesizes vowel bursts using formant synthesis with a noise layer.
|
||||||
|
* Triggered per-vowel by the parser's token stream. Vowels are filtered
|
||||||
|
* through three resonant formants (F1, F2, F3); consonants are silent.
|
||||||
|
* A breath layer adds texture, more so for whisper.
|
||||||
|
*
|
||||||
|
* Pitch is driven by sentence contours (statement, question, exclamation,
|
||||||
|
* ellipsis) combined multiplicatively with emotion presets, uppercase
|
||||||
|
* shouting, and `{voice}` overrides. Per-vowel jitter adds organic variance.
|
||||||
|
*
|
||||||
|
* On-demand, main thread. No caching. No SFX — non-speech synthesis is a
|
||||||
|
* separate future module.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { ParsedMessage, SentenceType, VoiceMood, Vowel } from "./chatter-types.ts";
|
||||||
|
import {
|
||||||
|
DEFAULT_VOICE,
|
||||||
|
VOWEL_FORMANTS,
|
||||||
|
type ContourConfig,
|
||||||
|
type EmotionConfig,
|
||||||
|
type VoiceConfig,
|
||||||
|
} from "./chatter-types.ts";
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Constants */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
const REFERENCE_F0 = 200; // Hz at basePitch = 1.0
|
||||||
|
const MAX_BURST_DURATION = 0.2; // cap on per-burst length
|
||||||
|
const MIN_BURST_DURATION = 0.03; // floor on per-burst length
|
||||||
|
const BURST_DURATION_MULTIPLIER = 1.5;
|
||||||
|
const SCHEDULING_DELAY = 0.02; // 20ms ahead for scheduling safety
|
||||||
|
const SYNTHESIS_LEAD_TIME = 0.08; // 80ms lead for spreading CPU load
|
||||||
|
const SYNTHESIS_AMPLITUDE = 0.2; // per-burst base amplitude
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Types */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export interface ScheduledBurst {
|
||||||
|
/** Seconds from message start. */
|
||||||
|
atTime: number;
|
||||||
|
/** Duration of the burst in seconds (already clamped and timeScale-adjusted). */
|
||||||
|
burstDuration: number;
|
||||||
|
/** Target F0 in Hz after all multipliers. */
|
||||||
|
pitch: number;
|
||||||
|
/** Formant frequency multiplier. */
|
||||||
|
formantScale: number;
|
||||||
|
/** 0..1 noise mix. */
|
||||||
|
noiseMix: number;
|
||||||
|
/** 0..1 volume. */
|
||||||
|
volume: number;
|
||||||
|
/** Which vowel to synthesize. */
|
||||||
|
vowel: Vowel;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlanMumbleOptions {
|
||||||
|
rng?: () => number;
|
||||||
|
timeScale?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MumbleOptions {
|
||||||
|
rng?: () => number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Plan (pure) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute the full burst schedule for a parsed message.
|
||||||
|
* Pure — no audio context, no side effects, deterministic given the rng.
|
||||||
|
* Tests target this function.
|
||||||
|
*/
|
||||||
|
export function planMumble(
|
||||||
|
parsed: ParsedMessage,
|
||||||
|
voice: VoiceConfig,
|
||||||
|
options: PlanMumbleOptions = {},
|
||||||
|
): ScheduledBurst[] {
|
||||||
|
const rng = options.rng ?? Math.random;
|
||||||
|
const timeScale = Math.max(0.01, options.timeScale ?? 1);
|
||||||
|
|
||||||
|
const merged = mergeVoice(voice, DEFAULT_VOICE);
|
||||||
|
const basePitch = merged.basePitch;
|
||||||
|
const formantScale = merged.formantScale;
|
||||||
|
const baseNoise = merged.noiseMix;
|
||||||
|
const baseVolume = merged.volume;
|
||||||
|
|
||||||
|
// Per-sentence start times and durations
|
||||||
|
const sentenceStarts: number[] = [];
|
||||||
|
const sentenceDurations: number[] = [];
|
||||||
|
let accum = 0;
|
||||||
|
for (const s of parsed.sentences) {
|
||||||
|
sentenceStarts.push(accum);
|
||||||
|
let dur = 0;
|
||||||
|
for (let i = s.startToken; i <= s.endToken; i++) {
|
||||||
|
const tok = parsed.tokens[i];
|
||||||
|
if (tok) dur += tok.duration;
|
||||||
|
}
|
||||||
|
sentenceDurations.push(dur);
|
||||||
|
accum += dur;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Token -> sentence index
|
||||||
|
const sentenceOfToken: number[] = new Array(parsed.tokens.length).fill(0);
|
||||||
|
for (let s = 0; s < parsed.sentences.length; s++) {
|
||||||
|
const si = parsed.sentences[s]!;
|
||||||
|
for (let i = si.startToken; i <= si.endToken; i++) {
|
||||||
|
sentenceOfToken[i] = s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: ScheduledBurst[] = [];
|
||||||
|
let timeOffset = 0;
|
||||||
|
let currentPitchMult = 1;
|
||||||
|
let currentVolumeMult = 1;
|
||||||
|
let currentMood: VoiceMood | null = null;
|
||||||
|
|
||||||
|
for (let i = 0; i < parsed.tokens.length; i++) {
|
||||||
|
const token = parsed.tokens[i]!;
|
||||||
|
|
||||||
|
// Non-timed tokens — mutate voice state only
|
||||||
|
if (token.kind === "voice") {
|
||||||
|
if (token.mood !== undefined) currentMood = token.mood;
|
||||||
|
if (token.pitch !== undefined) currentPitchMult = token.pitch;
|
||||||
|
if (token.volume !== undefined) currentVolumeMult = token.volume;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.kind === "speed") continue;
|
||||||
|
if (token.kind === "style-open" || token.kind === "style-close") continue;
|
||||||
|
|
||||||
|
// Timed but silent
|
||||||
|
if (token.kind === "pause" || token.kind === "icon") {
|
||||||
|
timeOffset += token.duration;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token.kind === "char") {
|
||||||
|
if (token.isVowel && token.vowel !== undefined) {
|
||||||
|
const si = sentenceOfToken[i]!;
|
||||||
|
const sent = parsed.sentences[si]!;
|
||||||
|
const sentStart = sentenceStarts[si]!;
|
||||||
|
const sentDur = sentenceDurations[si]!;
|
||||||
|
const elapsedInSentence = timeOffset - sentStart;
|
||||||
|
const tNorm = sentDur > 0 ? Math.min(1, Math.max(0, elapsedInSentence / sentDur)) : 0;
|
||||||
|
|
||||||
|
const contourCfg = merged.contours[sent.type];
|
||||||
|
const contourMult = computeContour(contourCfg, tNorm);
|
||||||
|
|
||||||
|
const emotionCfg: EmotionConfig | null = currentMood ? merged.emotions[currentMood] : null;
|
||||||
|
const emotionMult = emotionCfg?.pitch ?? 1;
|
||||||
|
const emotionNoise = emotionCfg?.noiseBonus ?? 0;
|
||||||
|
|
||||||
|
const shoutMult = token.shout ? 1.2 : 1;
|
||||||
|
const variation = 1 + (rng() - 0.5) * 0.04;
|
||||||
|
|
||||||
|
const finalPitch =
|
||||||
|
REFERENCE_F0 * basePitch * contourMult * emotionMult * currentPitchMult * shoutMult * variation;
|
||||||
|
|
||||||
|
const rawDur = token.duration * BURST_DURATION_MULTIPLIER;
|
||||||
|
const clampedDur = Math.min(MAX_BURST_DURATION, Math.max(MIN_BURST_DURATION, rawDur));
|
||||||
|
const scaledDur = clampedDur / timeScale;
|
||||||
|
|
||||||
|
result.push({
|
||||||
|
atTime: timeOffset / timeScale,
|
||||||
|
burstDuration: scaledDur,
|
||||||
|
pitch: finalPitch,
|
||||||
|
formantScale,
|
||||||
|
noiseMix: Math.min(1, baseNoise + emotionNoise),
|
||||||
|
volume: baseVolume * currentVolumeMult,
|
||||||
|
vowel: token.vowel,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
timeOffset += token.duration;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Synthesize (pure) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Synthesize a single vowel burst to a Float32Array.
|
||||||
|
*
|
||||||
|
* Formant synthesis: a harmonic-rich source at F0 is filtered through
|
||||||
|
* three resonant filters (F1, F2, F3), then mixed with filtered noise
|
||||||
|
* for breathiness. An attack-sustain-release envelope shapes the result.
|
||||||
|
*/
|
||||||
|
export function synthesizeVowel(
|
||||||
|
vowel: Vowel,
|
||||||
|
pitch: number,
|
||||||
|
duration: number,
|
||||||
|
sampleRate: number,
|
||||||
|
noiseMix: number,
|
||||||
|
formantScale: number,
|
||||||
|
volume: number,
|
||||||
|
rng: () => number = Math.random,
|
||||||
|
): Float32Array<ArrayBuffer> {
|
||||||
|
const numSamples = Math.max(1, Math.floor(sampleRate * duration));
|
||||||
|
const out = new Float32Array(numSamples);
|
||||||
|
|
||||||
|
const formants = VOWEL_FORMANTS[vowel];
|
||||||
|
const f1 = formants.f1 * formantScale;
|
||||||
|
const f2 = formants.f2 * formantScale;
|
||||||
|
const f3 = formants.f3 * formantScale;
|
||||||
|
|
||||||
|
const bq1 = makeResonator(f1, sampleRate);
|
||||||
|
const bq2 = makeResonator(f2, sampleRate);
|
||||||
|
const bq3 = makeResonator(f3, sampleRate);
|
||||||
|
const noiseLP = makeLowpass(3500, sampleRate);
|
||||||
|
|
||||||
|
const maxHarmonics = Math.min(10, Math.max(1, Math.floor(sampleRate / 2 / pitch)));
|
||||||
|
const phases = new Float32Array(maxHarmonics);
|
||||||
|
const phaseStep = (2 * Math.PI * pitch) / sampleRate;
|
||||||
|
const TWO_PI = Math.PI * 2;
|
||||||
|
|
||||||
|
const attackSamples = Math.min(Math.floor(sampleRate * 0.012), Math.floor(numSamples * 0.2));
|
||||||
|
const releaseSamples = Math.min(Math.floor(sampleRate * 0.03), Math.floor(numSamples * 0.4));
|
||||||
|
const sustainEnd = numSamples - releaseSamples;
|
||||||
|
|
||||||
|
for (let i = 0; i < numSamples; i++) {
|
||||||
|
// Source: additive harmonics
|
||||||
|
let source = 0;
|
||||||
|
for (let k = 0; k < maxHarmonics; k++) {
|
||||||
|
source += Math.sin(phases[k]!) / (k + 1);
|
||||||
|
phases[k] = (phases[k]! + phaseStep * (k + 1)) % TWO_PI;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Formant filters
|
||||||
|
const o1 = bq1.step(source);
|
||||||
|
const o2 = bq2.step(source);
|
||||||
|
const o3 = bq3.step(source);
|
||||||
|
const vowelSig = o1 * 1.0 + o2 * 0.55 + o3 * 0.25;
|
||||||
|
|
||||||
|
// Noise
|
||||||
|
const noise = rng() * 2 - 1;
|
||||||
|
const noiseSig = noiseLP.step(noise);
|
||||||
|
const mixed = (1 - noiseMix) * vowelSig + noiseMix * noiseSig * 2.5;
|
||||||
|
|
||||||
|
// Envelope
|
||||||
|
let env = 1;
|
||||||
|
if (i < attackSamples) env = i / attackSamples;
|
||||||
|
else if (i >= sustainEnd) {
|
||||||
|
env = Math.max(0, (numSamples - i) / releaseSamples);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Soft limit + volume + amplitude
|
||||||
|
const v = mixed * env * volume * SYNTHESIS_AMPLITUDE;
|
||||||
|
out[i] = Math.tanh(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Mumble */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export class Mumble {
|
||||||
|
private ctx: AudioContext | null = null;
|
||||||
|
private masterGain: GainNode | null = null;
|
||||||
|
|
||||||
|
private muted = false;
|
||||||
|
private timeScale = 1;
|
||||||
|
private voiceDefaults: VoiceConfig = {};
|
||||||
|
private readonly rng: () => number;
|
||||||
|
|
||||||
|
/** Per-entity active sources, so one entity's speech doesn't stop another's. */
|
||||||
|
private readonly sourcesByEntity = new Map<string, Set<AudioBufferSourceNode>>();
|
||||||
|
/** Per-entity pending synthesis timers. */
|
||||||
|
private readonly timersByEntity = new Map<string, Set<ReturnType<typeof setTimeout>>>();
|
||||||
|
|
||||||
|
constructor(options: MumbleOptions = {}) {
|
||||||
|
this.rng = options.rng ?? Math.random;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------- */
|
||||||
|
/* Lifecycle */
|
||||||
|
/* -------------------------------------------------------------- */
|
||||||
|
|
||||||
|
attach(ctx: AudioContext): void {
|
||||||
|
this.detach();
|
||||||
|
this.ctx = ctx;
|
||||||
|
this.masterGain = ctx.createGain();
|
||||||
|
this.masterGain.gain.value = 0.7;
|
||||||
|
this.masterGain.connect(ctx.destination);
|
||||||
|
}
|
||||||
|
|
||||||
|
detach(): void {
|
||||||
|
this.stopAll();
|
||||||
|
if (this.masterGain !== null) {
|
||||||
|
try {
|
||||||
|
this.masterGain.disconnect();
|
||||||
|
} catch {
|
||||||
|
// Node already disconnected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.ctx = null;
|
||||||
|
this.masterGain = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
isAvailable(): boolean {
|
||||||
|
return this.ctx !== null && this.masterGain !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------- */
|
||||||
|
/* Config */
|
||||||
|
/* -------------------------------------------------------------- */
|
||||||
|
|
||||||
|
setVoiceDefaults(voice: VoiceConfig): void {
|
||||||
|
this.voiceDefaults = voice;
|
||||||
|
}
|
||||||
|
|
||||||
|
setMuted(muted: boolean): void {
|
||||||
|
this.muted = muted;
|
||||||
|
if (muted) this.stopAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
isMuted(): boolean {
|
||||||
|
return this.muted;
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeScale(scale: number): void {
|
||||||
|
this.timeScale = Math.max(0.01, scale);
|
||||||
|
// Existing sources keep their rate — new messages get the new scale.
|
||||||
|
// Changing mid-playback isn't supported cleanly without re-scheduling.
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------- */
|
||||||
|
/* Speak */
|
||||||
|
/* -------------------------------------------------------------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Speak a parsed message for an entity.
|
||||||
|
* Stops any previous speech for the same entity.
|
||||||
|
* No-op silently if no AudioContext or muted.
|
||||||
|
*/
|
||||||
|
speak(entityId: string, parsed: ParsedMessage, voice?: VoiceConfig): void {
|
||||||
|
if (!this.ctx || !this.masterGain) return;
|
||||||
|
if (this.muted) return;
|
||||||
|
if (this.ctx.state === "suspended") void this.ctx.resume();
|
||||||
|
|
||||||
|
this.stop(entityId);
|
||||||
|
|
||||||
|
const merged = mergeVoice(voice ?? this.voiceDefaults, this.voiceDefaults);
|
||||||
|
const schedule = planMumble(parsed, merged, {
|
||||||
|
rng: this.rng,
|
||||||
|
timeScale: this.timeScale,
|
||||||
|
});
|
||||||
|
|
||||||
|
const now = this.ctx.currentTime;
|
||||||
|
const baseTime = now + SCHEDULING_DELAY;
|
||||||
|
|
||||||
|
const sources = new Set<AudioBufferSourceNode>();
|
||||||
|
const timers = new Set<ReturnType<typeof setTimeout>>();
|
||||||
|
this.sourcesByEntity.set(entityId, sources);
|
||||||
|
this.timersByEntity.set(entityId, timers);
|
||||||
|
|
||||||
|
for (const burst of schedule) {
|
||||||
|
const playAt = baseTime + burst.atTime;
|
||||||
|
const delay = playAt - now;
|
||||||
|
|
||||||
|
if (delay < SYNTHESIS_LEAD_TIME) {
|
||||||
|
this.playBurst(entityId, burst, playAt, sources);
|
||||||
|
} else {
|
||||||
|
const timer = setTimeout(
|
||||||
|
() => {
|
||||||
|
timers.delete(timer);
|
||||||
|
if (this.ctx && this.sourcesByEntity.get(entityId) === sources) {
|
||||||
|
this.playBurst(entityId, burst, playAt, sources);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Math.max(0, (delay - SYNTHESIS_LEAD_TIME) * 1000),
|
||||||
|
);
|
||||||
|
timers.add(timer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stop speech for one entity. Clears its pending bursts and cuts active ones. */
|
||||||
|
stop(entityId: string): void {
|
||||||
|
const sources = this.sourcesByEntity.get(entityId);
|
||||||
|
if (sources) {
|
||||||
|
for (const src of sources) {
|
||||||
|
try {
|
||||||
|
src.stop();
|
||||||
|
} catch {
|
||||||
|
// Already stopped
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sources.clear();
|
||||||
|
}
|
||||||
|
const timers = this.timersByEntity.get(entityId);
|
||||||
|
if (timers) {
|
||||||
|
for (const t of timers) clearTimeout(t);
|
||||||
|
timers.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stop all speech across entities. */
|
||||||
|
stopAll(): void {
|
||||||
|
for (const entityId of [...this.sourcesByEntity.keys()]) this.stop(entityId);
|
||||||
|
this.sourcesByEntity.clear();
|
||||||
|
this.timersByEntity.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------- */
|
||||||
|
/* Playback */
|
||||||
|
/* -------------------------------------------------------------- */
|
||||||
|
|
||||||
|
private playBurst(
|
||||||
|
entityId: string,
|
||||||
|
burst: ScheduledBurst,
|
||||||
|
playAt: number,
|
||||||
|
sources: Set<AudioBufferSourceNode>,
|
||||||
|
): void {
|
||||||
|
if (!this.ctx || !this.masterGain) return;
|
||||||
|
|
||||||
|
const samples = synthesizeVowel(
|
||||||
|
burst.vowel,
|
||||||
|
burst.pitch,
|
||||||
|
burst.burstDuration,
|
||||||
|
this.ctx.sampleRate,
|
||||||
|
burst.noiseMix,
|
||||||
|
burst.formantScale,
|
||||||
|
burst.volume,
|
||||||
|
this.rng,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (samples.length === 0) return;
|
||||||
|
|
||||||
|
const buffer = this.ctx.createBuffer(1, samples.length, this.ctx.sampleRate);
|
||||||
|
buffer.copyToChannel(samples, 0);
|
||||||
|
|
||||||
|
const source = this.ctx.createBufferSource();
|
||||||
|
source.buffer = buffer;
|
||||||
|
source.connect(this.masterGain);
|
||||||
|
|
||||||
|
source.onended = () => {
|
||||||
|
sources.delete(source);
|
||||||
|
try {
|
||||||
|
source.disconnect();
|
||||||
|
} catch {
|
||||||
|
// Already disconnected
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
source.start(playAt);
|
||||||
|
sources.add(source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Helpers */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
interface Filter {
|
||||||
|
step(x: number): number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeResonator(freq: number, sampleRate: number, bandwidth = 100): Filter {
|
||||||
|
// Two-pole resonator with unity gain at resonance.
|
||||||
|
const r = Math.exp((-Math.PI * bandwidth) / sampleRate);
|
||||||
|
const theta = (2 * Math.PI * freq) / sampleRate;
|
||||||
|
const a1 = 2 * r * Math.cos(theta);
|
||||||
|
const a2 = -r * r;
|
||||||
|
const b0 = (1 - r) * Math.sqrt(1 - 2 * r * Math.cos(2 * theta) + r * r);
|
||||||
|
|
||||||
|
let y1 = 0;
|
||||||
|
let y2 = 0;
|
||||||
|
return {
|
||||||
|
step(x: number): number {
|
||||||
|
const y = b0 * x + a1 * y1 + a2 * y2;
|
||||||
|
y2 = y1;
|
||||||
|
y1 = y;
|
||||||
|
return y;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeLowpass(freq: number, sampleRate: number): Filter {
|
||||||
|
// One-pole lowpass for noise shaping.
|
||||||
|
const rc = 1 / (2 * Math.PI * freq);
|
||||||
|
const dt = 1 / sampleRate;
|
||||||
|
const alpha = dt / (rc + dt);
|
||||||
|
let prev = 0;
|
||||||
|
return {
|
||||||
|
step(x: number): number {
|
||||||
|
prev = prev + alpha * (x - prev);
|
||||||
|
return prev;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeContour(cfg: ContourConfig, tNorm: number): number {
|
||||||
|
const eased = applyEase(tNorm, cfg.ease ?? "linear");
|
||||||
|
return cfg.from + (cfg.to - cfg.from) * eased;
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyEase(t: number, ease: string): number {
|
||||||
|
switch (ease) {
|
||||||
|
case "ease-in":
|
||||||
|
return t * t;
|
||||||
|
case "ease-out":
|
||||||
|
return 1 - (1 - t) * (1 - t);
|
||||||
|
case "ease-in-out":
|
||||||
|
return t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);
|
||||||
|
default:
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeVoice(override: VoiceConfig, fallback: VoiceConfig): typeof DEFAULT_VOICE {
|
||||||
|
const emotions: Record<VoiceMood, EmotionConfig> = {
|
||||||
|
...DEFAULT_VOICE.emotions,
|
||||||
|
...fallback.emotions,
|
||||||
|
...override.emotions,
|
||||||
|
};
|
||||||
|
const contours: Record<SentenceType, ContourConfig> = {
|
||||||
|
...DEFAULT_VOICE.contours,
|
||||||
|
...fallback.contours,
|
||||||
|
...override.contours,
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
basePitch: override.basePitch ?? fallback.basePitch ?? DEFAULT_VOICE.basePitch,
|
||||||
|
formantScale: override.formantScale ?? fallback.formantScale ?? DEFAULT_VOICE.formantScale,
|
||||||
|
noiseMix: override.noiseMix ?? fallback.noiseMix ?? DEFAULT_VOICE.noiseMix,
|
||||||
|
volume: override.volume ?? fallback.volume ?? DEFAULT_VOICE.volume,
|
||||||
|
emotions,
|
||||||
|
contours,
|
||||||
|
};
|
||||||
|
}
|
||||||
+54
-3
@@ -2,7 +2,7 @@
|
|||||||
import {
|
import {
|
||||||
angleFromPoint, AssetCache, BehaviorController, Canvas2DRenderer,
|
angleFromPoint, AssetCache, BehaviorController, Canvas2DRenderer,
|
||||||
ChatterOverlay,
|
ChatterOverlay,
|
||||||
distanceBetween, type AnimationClip,
|
distanceBetween, Mumble, type AnimationClip,
|
||||||
type BehaviorState, type BubbleRenderData, type CacheStats, type DebugSnapshot,
|
type BehaviorState, type BubbleRenderData, type CacheStats, type DebugSnapshot,
|
||||||
type EventDef,
|
type EventDef,
|
||||||
type LookSector
|
type LookSector
|
||||||
@@ -365,6 +365,24 @@
|
|||||||
const ro = new ResizeObserver(resize);
|
const ro = new ResizeObserver(resize);
|
||||||
ro.observe(canvas);
|
ro.observe(canvas);
|
||||||
|
|
||||||
|
const mumble = new Mumble();
|
||||||
|
let audioCtx: AudioContext | null = null;
|
||||||
|
|
||||||
|
const unlockAudio = async () => {
|
||||||
|
if(audioCtx) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
audioCtx = new AudioContext();
|
||||||
|
await audioCtx.resume();
|
||||||
|
mumble.attach(audioCtx);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[demo] audio unavailable', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('keydown', unlockAudio, {once: true});
|
||||||
|
window.addEventListener('pointerdown', unlockAudio, {once: true});
|
||||||
|
|
||||||
/* ---------------- pointer input ---------------- */
|
/* ---------------- pointer input ---------------- */
|
||||||
|
|
||||||
const cursorPos = { x: 0, y: 0 };
|
const cursorPos = { x: 0, y: 0 };
|
||||||
@@ -413,7 +431,7 @@
|
|||||||
|
|
||||||
/* ---------------- chatter overlay ---------------- */
|
/* ---------------- chatter overlay ---------------- */
|
||||||
|
|
||||||
const overlay = new ChatterOverlay();
|
const overlay = new ChatterOverlay({mumble});
|
||||||
const bubbleImg = makeBubbleImage(240, 100);
|
const bubbleImg = makeBubbleImage(240, 100);
|
||||||
const heartIcon = makeHeartIcon();
|
const heartIcon = makeHeartIcon();
|
||||||
overlay.registerIcon('heart', heartIcon);
|
overlay.registerIcon('heart', heartIcon);
|
||||||
@@ -432,7 +450,12 @@
|
|||||||
lineHeight: 1.3,
|
lineHeight: 1.3,
|
||||||
speed: 18
|
speed: 18
|
||||||
},
|
},
|
||||||
timing: { holdLast: 1.8 }
|
timing: { holdLast: 1.8 },
|
||||||
|
voice: {
|
||||||
|
basePitch: 1.5,
|
||||||
|
formantScale: 1.3,
|
||||||
|
volume: 0.7
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/* ---------------- controller ---------------- */
|
/* ---------------- controller ---------------- */
|
||||||
@@ -685,12 +708,37 @@
|
|||||||
raf = requestAnimationFrame(draw);
|
raf = requestAnimationFrame(draw);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (import.meta.env.DEV) {
|
||||||
|
(window as any).__demo = {
|
||||||
|
overlay,
|
||||||
|
mumble,
|
||||||
|
ctrl,
|
||||||
|
unlockAudio,
|
||||||
|
builtStates,
|
||||||
|
get audioState() {
|
||||||
|
return audioCtx?.state ?? 'not-created';
|
||||||
|
},
|
||||||
|
say: (text: string) => {
|
||||||
|
void unlockAudio();
|
||||||
|
overlay.say('cat', text);
|
||||||
|
},
|
||||||
|
stop: () => mumble.stopAll(),
|
||||||
|
skip: () => overlay.skip('cat'),
|
||||||
|
dismiss: () => overlay.dismiss('cat'),
|
||||||
|
clear: () => overlay.clear('cat'),
|
||||||
|
progress: () => overlay.progress('cat'),
|
||||||
|
pushEvent: (state: string, name: string) => ctrl.pushEvent(state, name),
|
||||||
|
voice: (v: Parameters<typeof mumble.setVoiceDefaults>[0]) => mumble.setVoiceDefaults(v)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
raf = requestAnimationFrame(draw);
|
raf = requestAnimationFrame(draw);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
errorMsg = err instanceof Error ? err.message : String(err);
|
errorMsg = err instanceof Error ? err.message : String(err);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
@@ -698,6 +746,9 @@
|
|||||||
ro.disconnect();
|
ro.disconnect();
|
||||||
window.removeEventListener('pointermove', onPointerMove);
|
window.removeEventListener('pointermove', onPointerMove);
|
||||||
window.removeEventListener('pointerleave', onPointerLeave);
|
window.removeEventListener('pointerleave', onPointerLeave);
|
||||||
|
mumble.detach();
|
||||||
|
if(audioCtx) void audioCtx.close();
|
||||||
|
if (import.meta.env.DEV) delete (window as any).__demo;
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user