Skip to content

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

Rust

Main buttons: a failed start offers a retry, not a silent Stop; menus don't play notes (review)

Jameson Hodgee41e214bc680
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index 0021531..c7a86bd 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -139,18 +139,12 @@ function LeftScreen() {
/** Play's main button: breathe (the voice sounds while it's on), and Whisper beside it. */
function PlayActions() {
const hold = useStore((s) => s.hold);
- const setHold = useStore((s) => s.setHold);
- const start = useStore((s) => s.start);
+ const toggleBreath = useStore((s) => s.toggleBreath);
const voiced = useStore((s) => s.source.voiced);
const setSource = useStore((s) => s.setSource);
- const breathe = async () => {
- if (hold) return setHold(false);
- await start();
- if (useStore.getState().started) setHold(true);
- };
return (
- <ActionBar label="Voice" onSpace={() => void breathe()}>
- <PrimaryButton label="Breathe" icon="breath" playing={hold} onClick={() => void breathe()} />
+ <ActionBar label="Voice" onSpace={() => void toggleBreath()}>
+ <PrimaryButton label="Breathe" icon="breath" playing={hold} onClick={() => void toggleBreath()} />
<Chip on={!voiced} onClick={() => setSource({ voiced: !voiced })}>
Whisper
</Chip>
diff --git a/src/ui/components/ActionBar.tsx b/src/ui/components/ActionBar.tsx
index 0c91874..ce15011 100644
--- a/src/ui/components/ActionBar.tsx
+++ b/src/ui/components/ActionBar.tsx
@@ -37,12 +37,15 @@ export function ActionBar(props: { label: string; onSpace: () => void; children:
);
}
-/** The bright button (amber: it makes sound). While its sound plays it reads Stop. */
-export function PrimaryButton(props: { label: string; playing?: boolean; busy?: string | null; icon?: "play" | "breath"; className?: string; onClick: () => void }) {
+/**
+ * The bright button (amber: it makes sound). While its sound plays it reads Stop. While the audio
+ * starts, every main button waits, and the one pressed (`pressed`, default all) says so.
+ */
+export function PrimaryButton(props: { label: string; playing?: boolean; busy?: string | null; pressed?: boolean; icon?: "play" | "breath"; className?: string; title?: string; onClick: () => void }) {
const starting = useStore((s) => s.starting);
- const text = starting ? "Starting…" : props.busy ? props.busy : props.playing ? "Stop" : props.label;
+ const text = starting && props.pressed !== false ? "Starting…" : props.busy ? props.busy : props.playing ? "Stop" : props.label;
return (
- <button type="button" className={`act-primary${props.playing ? " on" : ""}${props.className ? " " + props.className : ""}`} onClick={props.onClick} disabled={starting || !!props.busy}>
+ <button type="button" className={`act-primary${props.playing ? " on" : ""}${props.className ? " " + props.className : ""}`} onClick={props.onClick} disabled={starting || !!props.busy} title={props.title}>
<span className={`act-icon ${props.playing ? "stop" : (props.icon ?? "play")}`} aria-hidden="true" />
{text}
</button>
diff --git a/src/ui/components/BeatboxPanel.tsx b/src/ui/components/BeatboxPanel.tsx
index 0cfe2b4..794c45d 100644
--- a/src/ui/components/BeatboxPanel.tsx
+++ b/src/ui/components/BeatboxPanel.tsx
@@ -64,6 +64,7 @@ function Pads() {
const onKey = (e: KeyboardEvent) => {
if (e.repeat || e.metaKey || e.ctrlKey || e.altKey) return;
const t = e.target as HTMLElement;
+ if (t && t.tagName === "SELECT") return;
if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA") && (t as HTMLInputElement).type !== "range" && (t as HTMLInputElement).type !== "checkbox") return;
const i = "1234567890".indexOf(e.key);
if (i >= 0 && i < BEAT_SOUNDS.length) {
diff --git a/src/ui/components/BestiaryPanel.tsx b/src/ui/components/BestiaryPanel.tsx
index ef2ccd4..ab8565c 100644
--- a/src/ui/components/BestiaryPanel.tsx
+++ b/src/ui/components/BestiaryPanel.tsx
@@ -4,7 +4,8 @@ import { CREATURES, creatureById } from "../../wasm/engine.ts";
import type { CreatureDef } from "../../wasm/types.ts";
import { useLiveCreature } from "../creatureLive.ts";
import { Keys, MidiButton } from "./Keys.tsx";
-import { ActionBar } from "./ActionBar.tsx";
+import { ActionBar, PrimaryButton } from "./ActionBar.tsx";
+import { engine } from "../../audio/AudioEngine.ts";
import { Menu } from "./Controls.tsx";
import { Chip, Screen } from "./Screen.tsx";
import { EncoderPages, type EncoderPage } from "./Encoder.tsx";
@@ -45,31 +46,29 @@ function Gallery() {
}
/**
- * Bestiary's main buttons: the animal's calls (each one plays it; the one sounding is lit), and
- * Breathe, which keeps the breath on to shape the sound with the controls. Space replays the last
- * call. (The animal's description is written under its name, on the creature screen.)
+ * Bestiary's main buttons: the animal's calls (each plays it; the one sounding reads Stop), and
+ * Breathe, which keeps the breath on to shape the sound with the controls. Space stops the call
+ * sounding, or plays the last one again. (The animal's description is written under its name, on
+ * the creature screen.)
*/
function CallActions({ def }: { def: CreatureDef }) {
const playCall = useStore((s) => s.playCall);
- const starting = useStore((s) => s.starting);
const hold = useStore((s) => s.hold);
- const setHold = useStore((s) => s.setHold);
- const live = useLiveCreature(def.id);
+ const toggleBreath = useStore((s) => s.toggleBreath);
+ const sounding = useLiveCreature(def.id)?.call ?? null;
const [last, setLast] = useState<string | null>(null);
- const play = (id: string) => {
+ const press = (id: string) => {
+ if (sounding === id) return engine.stopCall();
setLast(id);
playCall(id);
};
- const again = def.calls.find((c) => c.id === last) ?? def.calls[0];
+ const again = sounding ?? (def.calls.find((c) => c.id === last) ?? def.calls[0])?.id;
return (
- <ActionBar label="Calls" onSpace={() => again && play(again.id)}>
+ <ActionBar label="Calls" onSpace={() => again && press(again)}>
{def.calls.map((c) => (
- <button key={c.id} type="button" className={`act-primary act-call${live?.call === c.id ? " on" : ""}`} onClick={() => play(c.id)} disabled={starting} title={c.hint}>
- <span className="act-icon play" aria-hidden="true" />
- {c.name}
- </button>
+ <PrimaryButton key={c.id} className="act-call" label={c.name} playing={sounding === c.id} pressed={last === c.id} title={c.hint} onClick={() => press(c.id)} />
))}
- <Chip on={hold} onClick={() => setHold(!hold)} title="Keep the breath on and shape the sound with the controls">
+ <Chip on={hold} onClick={() => void toggleBreath()} title="Keep the breath on and shape the sound with the controls">
Breathe
</Chip>
</ActionBar>
diff --git a/src/ui/components/Keys.tsx b/src/ui/components/Keys.tsx
index dd935a4..861e798 100644
--- a/src/ui/components/Keys.tsx
+++ b/src/ui/components/Keys.tsx
@@ -32,6 +32,7 @@ export function Keys() {
const onDown = (e: KeyboardEvent) => {
if (e.repeat || e.metaKey || e.ctrlKey || e.altKey) return;
const target = e.target as HTMLElement;
+ if (target && target.tagName === "SELECT") return;
if (target && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)) {
if ((target as HTMLInputElement).type !== "range" && (target as HTMLInputElement).type !== "checkbox") return;
}
diff --git a/src/ui/components/SingPanel.tsx b/src/ui/components/SingPanel.tsx
index 27ec43b..3c8bcb9 100644
--- a/src/ui/components/SingPanel.tsx
+++ b/src/ui/components/SingPanel.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { useStore } from "../store.ts";
import { useSing, playDemo, stopSinging, soundingSyllable, sungNow, DEMO_SONGS, ensureDictionary } from "../singing.ts";
import { mouthWords } from "../mouthWords.ts";
@@ -114,17 +114,34 @@ function SongControls() {
);
}
-/** Sing's main button: sing the chosen song (its own words), or stop it. */
+/**
+ * Sing's main button: sing the chosen song (its own words), or stop it. A song getting ready
+ * (audio starting, the dictionary loading) counts as playing: Stop cancels it, and choosing
+ * another song replaces it.
+ */
function SingActions() {
const start = useStore((s) => s.start);
const demo = useSing((s) => s.demo);
const [song, setSong] = useState(DEMO_SONGS[0].name);
- // playDemo waits for the audio itself, so a stop meanwhile (body, mode) cancels it
- const sing = (name: string) => void playDemo(name, useStore.getState().body, start);
- const press = () => (demo ? stopSinging() : sing(song));
+ const [pending, setPending] = useState(false);
+ const request = useRef(0);
+ // the audio must be running: if it failed to start, nothing is planned and the error shows
+ const ready = async () => {
+ await start();
+ if (!useStore.getState().started) throw new Error("no audio");
+ };
+ // playDemo waits for `ready` itself, so a stop meanwhile (body, mode, another song) cancels it
+ const sing = (name: string) => {
+ const n = ++request.current;
+ setPending(true);
+ playDemo(name, useStore.getState().body, ready)
+ .catch(() => {})
+ .finally(() => request.current === n && setPending(false));
+ };
+ const press = () => (demo || pending ? stopSinging() : sing(song));
return (
<ActionBar label="Song" onSpace={press}>
- <PrimaryButton label="Sing" playing={!!demo} onClick={press} />
+ <PrimaryButton label="Sing" playing={!!demo || pending} onClick={press} />
<Menu
label="Song"
icon="note"
@@ -132,7 +149,7 @@ function SingActions() {
options={DEMO_SONGS.map((s) => ({ value: s.name, label: s.name }))}
onChange={(name) => {
setSong(name);
- if (demo) sing(name);
+ if (demo || pending) sing(name);
}}
/>
</ActionBar>
diff --git a/src/ui/components/SpeakPanel.tsx b/src/ui/components/SpeakPanel.tsx
index 15cab59..a49fbeb 100644
--- a/src/ui/components/SpeakPanel.tsx
+++ b/src/ui/components/SpeakPanel.tsx
@@ -146,6 +146,8 @@ export function SpeakRight() {
setBusy(true);
try {
await start();
+ // the audio didn't start (the error shows on the bar): speaking would only light Stop
+ if (!useStore.getState().started) return;
await speakText(text, { ipa, body, rate, f0 });
} finally {
setBusy(false);
@@ -153,6 +155,7 @@ export function SpeakRight() {
};
const pad = async (c: string) => {
await start();
+ if (!useStore.getState().started) return;
speakPhrases([{ segments: tokenizeIpa(`ˈ${vowel}${c}${vowel}`), intonation: "flat" }], { body, rate, f0 });
};
diff --git a/src/ui/store.ts b/src/ui/store.ts
index 348fb97..43061fa 100644
--- a/src/ui/store.ts
+++ b/src/ui/store.ts
@@ -77,6 +77,8 @@ interface State {
setArtic: (v: Partial<HumanArtic>, tipFree?: boolean) => void;
setVolume: (v: number) => void;
setHold: (h: boolean) => void;
+ /** Breathe: on (starting the audio first, if need be) or off */
+ toggleBreath: () => Promise<void>;
/** a key went down (velocity 1..127; the on-screen keys send 96) */
noteOn: (midi: number, velocity?: number) => void;
noteOff: (midi: number) => void;
@@ -216,7 +218,9 @@ export const useStore = create<State>((set, get) => ({
.start()
.then(() => {
const b = get().beat;
- if (get().started && b.playing) engine.setBeat({ steps: b.steps, bpm: b.bpm, swing: b.swing, playing: true });
+ // the audio didn't start: the beat isn't playing, so its button offers Play (a retry), not Stop
+ if (!get().started) set((s) => ({ beat: { ...s.beat, playing: false } }));
+ else if (b.playing) engine.setBeat({ steps: b.steps, bpm: b.bpm, swing: b.swing, playing: true });
});
},
loadBeatPreset: (name) => {
@@ -309,6 +313,14 @@ export const useStore = create<State>((set, get) => ({
set({ hold: h });
updateGate(get());
},
+ toggleBreath: async () => {
+ if (get().hold) return get().setHold(false);
+ const mode = get().mode;
+ 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);
+ },
noteOn: (midi, velocity = 96) => {
const held = get().heldNotes.filter((n) => n !== midi).concat(midi);
set({ heldNotes: held });
diff --git a/tests/singing-live.test.ts b/tests/singing-live.test.ts
index d3fe557..294290b 100644
--- a/tests/singing-live.test.ts
+++ b/tests/singing-live.test.ts
@@ -344,3 +344,40 @@ describe("settings that belong to one tab stay in it", () => {
done();
});
});
+
+describe("a main button pressed before the audio is up", () => {
+ const store = async () => (await import("../src/ui/store.ts")).useStore;
+ const failing = () => Promise.reject(new Error("no audio device"));
+
+ test("Breathe breathes once the audio starts, but not in a tab switched to meanwhile", async () => {
+ const useStore = await store();
+ useStore.setState({ started: false, mode: "play", hold: false });
+ let pending = useStore.getState().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
+ startAudio();
+ await pending;
+ expect(useStore.getState().hold).toBe(false);
+ });
+
+ test("a failed start leaves Breathe off and the beat stopped, so the buttons offer a retry", async () => {
+ const useStore = await store();
+ const start = engineStub.start;
+ engineStub.start = failing;
+ useStore.setState({ started: false, mode: "play", hold: false });
+ await useStore.getState().toggleBreath();
+ expect(useStore.getState().hold).toBe(false);
+ expect(useStore.getState().startError).toBe("no audio device");
+ useStore.getState().setMode("beatbox");
+ useStore.getState().setBeatPlaying(true);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(useStore.getState().beat.playing).toBe(false);
+ engineStub.start = start;
+ useStore.setState({ startError: null });
+ });
+});
diff --git a/tools/e2e.ts b/tools/e2e.ts
index c6effca..a03557d 100644
--- a/tools/e2e.ts
+++ b/tools/e2e.ts
@@ -131,6 +131,12 @@ async function run(viewport: { width: number; height: number }, tag: string) {
if (!(singing > 0.01)) errors.push(`[${tag}] a sung key made no sound (${singing})`);
if (!(after < 1e-3)) errors.push(`[${tag}] voice still sounding after the sung notes: ${after}`);
if (sylBefore === sylAfter) errors.push(`[${tag}] the syllable cursor did not move (${sylBefore})`);
+ // a menu isn't an instrument: a letter typed in it picks an entry, it doesn't play a note
+ await page.getByRole("combobox", { name: "Song" }).focus();
+ await page.keyboard.down("d");
+ const menuNotes = await page.locator(".keys .key.down").count();
+ await page.keyboard.up("d");
+ if (menuNotes) errors.push(`[${tag}] a key typed in the song menu played a note`);
await page.getByRole("combobox", { name: "Song" }).selectOption("Made of air");
await page.getByRole("button", { name: /^Sing$/ }).click();
await page.waitForTimeout(2200);
@@ -162,6 +168,20 @@ async function run(viewport: { width: number; height: number }, tag: string) {
});
logs.push(`[${tag}] creature ${name}: ${JSON.stringify(state)}`);
}
+ // the sounding call's button reads Stop, and stops it (start one if the last has ended)
+ const stop = page.getByRole("button", { name: /^Stop$/ });
+ if (!(await stop.count())) {
+ await page.locator(".act-call").first().click();
+ await page.waitForTimeout(500);
+ }
+ await stop.click();
+ await page.waitForTimeout(400);
+ const callAfterStop = await page.evaluate(() => {
+ // @ts-expect-error debug handle
+ return window.__chimeraEngine?.latestCreature?.t?.call ?? null;
+ });
+ logs.push(`[${tag}] creature call after Stop: ${callAfterStop}`);
+ if (callAfterStop !== null) errors.push(`[${tag}] the call kept sounding after Stop (${callAfterStop})`);
await page.keyboard.down("g");
await page.waitForTimeout(600);
const held = await page.evaluate(() => {