the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Retry after a failed audio start builds the audio again (it resumed an empty context): review 2
Jameson Hodgeebd704846e7f
diff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.tsindex dc1f9cd..770956f 100644--- a/src/audio/AudioEngine.ts+++ b/src/audio/AudioEngine.ts@@ -64,9 +64,18 @@ export class AudioEngine {const ctx = new AudioContext({ latencyHint: "interactive", sampleRate: 48000 });this.ctx = ctx;this.sampleRate = ctx.sampleRate;- await ctx.audioWorklet.addModule(workletUrl);- // the worklet instantiates the engine from the module compiled at startup (main.tsx)- const node = new AudioWorkletNode(ctx, "chimera", { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2], processorOptions: { module: chimeraModule() } });+ let node: AudioWorkletNode;+ try {+ await ctx.audioWorklet.addModule(workletUrl);+ // the worklet instantiates the engine from the module compiled at startup (main.tsx)+ node = new AudioWorkletNode(ctx, "chimera", { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2], processorOptions: { module: chimeraModule() } });+ } catch (e) {+ // without its worklet the context is empty: forget it, so a retry builds the graph again+ // instead of resuming a context with nothing in it (and reporting that the audio started)+ this.ctx = null;+ void ctx.close().catch(() => {});+ throw e;+ }this.node = node;const master = ctx.createGain();master.gain.value = 0.8;diff --git a/src/ui/components/SingPanel.tsx b/src/ui/components/SingPanel.tsxindex 3c8bcb9..576435b 100644--- a/src/ui/components/SingPanel.tsx+++ b/src/ui/components/SingPanel.tsx@@ -138,7 +138,12 @@ function SingActions() {.catch(() => {}).finally(() => request.current === n && setPending(false));};- const press = () => (demo || pending ? stopSinging() : sing(song));+ const stop = () => {+ request.current++; // the song getting ready, if any, no longer counts+ setPending(false);+ stopSinging();+ };+ const press = () => (demo || pending ? stop() : sing(song));return (<ActionBar label="Song" onSpace={press}><PrimaryButton label="Sing" playing={!!demo || pending} onClick={press} />diff --git a/src/ui/store.ts b/src/ui/store.tsindex 43061fa..e45bbef 100644--- a/src/ui/store.ts+++ b/src/ui/store.ts@@ -315,11 +315,12 @@ export const useStore = create<State>((set, get) => ({},toggleBreath: async () => {if (get().hold) return get().setHold(false);- const mode = get().mode;+ // on at once, so a second press while the audio starts turns it off again; switching tabs+ // meanwhile clears it as any switch does (setMode)+ get().setHold(true);await get().start();- // not if the audio failed to start, nor in a tab switched to meanwhile (Sing and Speak breathe- // by themselves, and a held breath would drone under them)- if (get().started && get().mode === mode) get().setHold(true);+ // the audio didn't start: nothing breathes, so the button offers Breathe (a retry) again+ if (!get().started) get().setHold(false);},noteOn: (midi, velocity = 96) => {const held = get().heldNotes.filter((n) => n !== midi).concat(midi);diff --git a/tests/singing-live.test.ts b/tests/singing-live.test.tsindex 294290b..64a9207 100644--- a/tests/singing-live.test.ts+++ b/tests/singing-live.test.ts@@ -351,18 +351,35 @@ describe("a main button pressed before the audio is up", () => {test("Breathe breathes once the audio starts, but not in a tab switched to meanwhile", async () => {const useStore = await store();+ const st = useStore.getState;useStore.setState({ started: false, mode: "play", hold: false });- let pending = useStore.getState().toggleBreath();+ let pending = st().toggleBreath();startAudio();await pending;- expect(useStore.getState().hold).toBe(true);- useStore.getState().setHold(false);- useStore.setState({ started: false });- pending = useStore.getState().toggleBreath();- useStore.getState().setMode("sing"); // Sing breathes by itself: a held breath would drone+ expect(st().hold).toBe(true);+ st().setHold(false);+ // a tab switched to meanwhile (Sing breathes by itself: a held breath would drone), and away+ // and back again: the press belonged to the Play the player left+ for (const away of [["sing"], ["sing", "play"]] as const) {+ useStore.setState({ started: false, mode: "play", hold: false });+ pending = st().toggleBreath();+ for (const m of away) st().setMode(m);+ startAudio();+ await pending;+ expect(st().hold).toBe(false);+ }+ });++ test("a second press of Breathe while the audio starts turns it off again", async () => {+ const useStore = await store();+ const st = useStore.getState;+ useStore.setState({ started: false, mode: "bestiary", hold: false });+ const first = st().toggleBreath();+ const second = st().toggleBreath();startAudio();- await pending;- expect(useStore.getState().hold).toBe(false);+ await Promise.all([first, second]);+ expect(st().hold).toBe(false);+ useStore.setState({ mode: "play" });});test("a failed start leaves Breathe off and the beat stopped, so the buttons offer a retry", async () => {diff --git a/tools/e2e.ts b/tools/e2e.tsindex a03557d..a2cbbec 100644--- a/tools/e2e.ts+++ b/tools/e2e.ts@@ -235,6 +235,37 @@ async function run(viewport: { width: number; height: number }, tag: string) {await page.close();}+// a start that failed (the worklet didn't load) can be retried from the same button: the retry+// builds the audio again instead of resuming the empty context and reporting success+{+ const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });+ page.on("pageerror", (e) => errors.push(`[retry] pageerror: ${e.message}`));+ // the worklet's fetch isn't the page's (route() never sees it): fail the first addModule instead+ await page.addInitScript(() => {+ const add = AudioWorklet.prototype.addModule;+ let calls = 0;+ AudioWorklet.prototype.addModule = function (this: AudioWorklet, ...a: Parameters<typeof add>) {+ (window as unknown as { __worklets: number }).__worklets = ++calls;+ return calls === 1 ? Promise.reject(new Error("worklet blocked by the test")) : add.apply(this, a);+ };+ });+ await page.goto(url, { waitUntil: "networkidle" });+ await page.getByRole("radio", { name: "Play" }).click();+ await page.getByRole("button", { name: /^Breathe$/ }).click();+ const failed = await page.getByText(/Audio could not start/).waitFor({ timeout: 10000 }).then(() => true, () => false);+ await page.getByRole("button", { name: /^Breathe$/ }).click();+ await page.waitForTimeout(1500);+ const running = await page.evaluate(() => {+ // @ts-expect-error debug handle+ return !!window.__chimeraEngine?.latest;+ });+ const worklets = await page.evaluate(() => (window as unknown as { __worklets?: number }).__worklets ?? 0);+ logs.push(`[retry] first start failed: ${failed}, worklet requests ${worklets}, running after retry: ${running}`);+ if (!failed) errors.push("[retry] blocking the worklet didn't make the first start fail");+ if (!running) errors.push(`[retry] the retry after a failed start didn't start the audio (${worklets} worklet requests)`);+ await page.close();+}+// the very first key in Sing mode, before audio has started, still sings once audio is up{const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });@@ -283,6 +314,6 @@ 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|rate|warn|transcription|creature|held|back to|beatbox|silence|sing|octave/i.test(l)).slice(0, 48).join("\n"));+console.log(logs.filter((l) => /load|rate|warn|transcription|creature|held|back to|beatbox|silence|sing|octave|retry/i.test(l)).slice(0, 52).join("\n"));// a run that collected errors fails, so CI and agents can't read it as a passif (errors.length) process.exit(1);