the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Vector display, phase 3: Sing
Jameson Hodgec791170d84d2
diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex ed7ac56..65aac01 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -18,7 +18,7 @@ import { Scope } from "./components/Scope.tsx";import { CreatureTubes } from "./components/CreatureTubes.tsx";import { creatureById } from "../wasm/engine.ts";import { BeatboxPanel, BeatOverlay } from "./components/BeatboxPanel.tsx";-import { SingPanel } from "./components/SingPanel.tsx";+import { SingRight, singInfo } from "./components/SingPanel.tsx";import { playDemo, DEMO_SONGS } from "./singing.ts";import type { Mode } from "./store.ts";import type { BodyName } from "../worklet/protocol.ts";@@ -157,7 +157,7 @@ function LeftScreen() {label={bestiary ? "Live creature airway" : "Live vocal tract"}tools={<ViewToggles />}>- {bestiary ? <CreatureView /> : mode === "speak" ? <AnatomyView slots={speechSlots} info={speechInfo} /> : <AnatomyView />}+ {bestiary ? <CreatureView /> : mode === "speak" ? <AnatomyView slots={speechSlots} info={speechInfo} /> : mode === "sing" ? <AnatomyView info={singInfo} /> : <AnatomyView />}{mode === "beatbox" && <BeatOverlay />}<StartPrompt /></Screen>@@ -212,7 +212,6 @@ function LegacyRight() {function Deck() {const mode = useStore((s) => s.mode);- if (mode === "sing") return <SingPanel />;if (mode === "bestiary") return <BestiaryPanel />;if (mode === "beatbox") return <BeatboxPanel />;return null;@@ -225,7 +224,7 @@ export function App() {<TopBar /><main className={`wall wall-${mode}`}><LeftScreen />- {mode === "play" ? <PlayRight /> : mode === "speak" ? <SpeakRight /> : <LegacyRight />}+ {mode === "play" ? <PlayRight /> : mode === "speak" ? <SpeakRight /> : mode === "sing" ? <SingRight /> : <LegacyRight />}</main><Deck /></div>diff --git a/src/ui/components/PianoRoll.tsx b/src/ui/components/PianoRoll.tsxindex 51cae2c..95e95ba 100644--- a/src/ui/components/PianoRoll.tsx+++ b/src/ui/components/PianoRoll.tsx@@ -1,9 +1,10 @@import { useRef } from "react";-import { useCanvasLoop, font } from "../useCanvas.ts";+import { usePhosphor } from "../usePhosphor.ts";import { engine } from "../../audio/AudioEngine.ts";import { useStore } from "../store.ts";import { roll, tickSinging } from "../singing.ts";-import { C } from "../colors.ts";+import { V } from "../colors.ts";+import { beam, beamPts, label, seg, type Pt } from "../render/vector.ts";/** pixels per second of voice time */const SPEED = 96;@@ -18,12 +19,13 @@ const KEY_CENTRE: Record<string, number> = { male: 54, female: 66, child: 70 };const hzToMidi = (f: number) => 69 + 12 * Math.log2(f / 440);/**- * Scrolling piano roll for Sing mode: the notes asked for (bars, with their syllables) and the- * pitch the vocal folds actually produced (a trace that shows the onsets, glides and vibrato).+ * Scrolling piano roll for Sing mode: the notes asked for (green frames, with their syllables)+ * and the pitch the vocal folds actually produced (an amber trace with the onsets, glides and+ * vibrato), on the vector display.*/export function PianoRoll() {const st = useRef({ centre: NaN, trace: [] as { t: number; m: number; v: number }[], lastClock: -1 });- const ref = useCanvasLoop(({ ctx, w, h, dt }) => {+ const ref = usePhosphor(({ ctx, w, h, dt }) => {tickSinging();const s = st.current;const body = useStore.getState().body;@@ -36,8 +38,9 @@ export function PianoRoll() {const cut = tele.clock - (w * NOW_AT) / SPEED - 1;while (s.trace.length && s.trace[0].t < cut) s.trace.shift();}- const tLeft = clock - (w * NOW_AT) / SPEED, tRight = clock + (w * (1 - NOW_AT)) / SPEED;- const x = (t: number) => (t - tLeft) * SPEED;+ const left = 34;+ const tLeft = clock - ((w - left) * NOW_AT) / SPEED, tRight = clock + ((w - left) * (1 - NOW_AT)) / SPEED;+ const x = (t: number) => left + (t - tLeft) * SPEED;// follow the notes on screen (slowly), else rest on the keyboard's middlelet lo = Infinity, hi = -Infinity;for (const n of roll.notes) {@@ -45,71 +48,71 @@ export function PianoRoll() {lo = Math.min(lo, n.midi);hi = Math.max(hi, n.midi);}- const want = lo <= hi ? (lo + hi) / 2 : KEY_CENTRE[body] ?? 60;+ const want = lo <= hi ? (lo + hi) / 2 : (KEY_CENTRE[body] ?? 60);if (!Number.isFinite(s.centre)) s.centre = want;s.centre += (want - s.centre) * (1 - Math.exp(-dt / 0.6));const bottom = s.centre - SPAN / 2;- const rowH = h / SPAN;- const y = (m: number) => h - (m - bottom + 0.5) * rowH;+ const top = 6;+ const rowH = (h - top - 4) / SPAN;+ const y = (m: number) => h - 4 - (m - bottom + 0.5) * rowH;- ctx.fillStyle = C.black;- ctx.fillRect(0, 0, w, h);- // keyboard rows: black-key rows a shade lighter, a line and a name at each C- ctx.font = font(10.5, 500);- ctx.textBaseline = "middle";+ // rows: a line at each C (named), dotted lines through the black keys+ const dotted = new Path2D();for (let m = Math.floor(bottom) - 1; m <= Math.ceil(bottom + SPAN) + 1; m++) {const pc = ((m % 12) + 12) % 12;const yc = y(m);+ if (yc < top || yc > h) continue;if (BLACK.includes(pc)) {- ctx.fillStyle = "#0b0d0e";- ctx.fillRect(0, yc - rowH / 2, w, rowH);+ dotted.moveTo(left, yc);+ dotted.lineTo(w, yc);}if (pc === 0) {- ctx.fillStyle = C.line;- ctx.fillRect(0, Math.round(yc + rowH / 2) - 0.5, w, 1);- ctx.fillStyle = C.textDim;- ctx.fillText(`${NAMES[pc]}${Math.floor(m / 12) - 1}`, 6, yc);+ seg(ctx, left, yc + rowH / 2, w, yc + rowH / 2, V.frame, 1);+ label(ctx, `${NAMES[pc]}${Math.floor(m / 12) - 1}`, 6, yc + 3, { size: 9, color: V.blueMid, ls: 0.1 });}}+ beam(ctx, dotted, V.frame, 1, { dash: [1, 5] });+// notes- const barH = Math.max(3, rowH - 2);- ctx.textBaseline = "alphabetic";- ctx.font = font(12, 550);+ const barH = Math.max(4, rowH - 3);for (const n of roll.notes) {const t1 = n.t1 ?? clock;if (t1 < tLeft || n.t0 > tRight) continue;- const x0 = x(n.t0), x1 = Math.max(x0 + 3, x(t1));+ const x0 = Math.max(left, x(n.t0)), x1 = Math.max(x0 + 3, x(t1));const yc = y(n.midi);const live = n.t0 <= clock && clock <= t1;- ctx.fillStyle = live ? C.caliper : n.t0 > clock ? "rgba(242, 207, 91, 0.32)" : "rgba(242, 207, 91, 0.58)";- ctx.beginPath();- ctx.roundRect(x0, yc - barH / 2, x1 - x0, barH, Math.min(3, barH / 2));- ctx.fill();- if (n.text && n.text !== "~") {- ctx.fillStyle = live ? C.text : C.textDim;- ctx.fillText(n.text, x0 + 1, yc - barH / 2 - 4);+ const future = n.t0 > clock;+ const r = new Path2D();+ r.rect(x0, yc - barH / 2, x1 - x0, barH);+ if (live) {+ ctx.save();+ ctx.globalCompositeOperation = "lighter";+ ctx.fillStyle = "rgba(91, 227, 129, 0.12)";+ ctx.fill(r);+ ctx.restore();}+ beam(ctx, r, V.green, live ? 1.6 : 1.2, { alpha: live ? 1 : future ? 0.38 : 0.62, hot: live });+ if (n.text && n.text !== "~") label(ctx, n.text.toUpperCase(), x0 + 1, yc - barH / 2 - 4, { size: 10, color: live ? V.white : V.blueMid, ls: 0.12, alpha: future ? 0.6 : 1 });}+// the pitch actually sung- ctx.strokeStyle = "rgb(240, 88, 28)";- ctx.lineWidth = 1.6;- ctx.lineJoin = "round";- ctx.beginPath();- let pen = false;+ let run: Pt[] = [];+ const flush = () => {+ if (run.length > 1) beamPts(ctx, run, V.amber, 1.5, { hot: true });+ run = [];+ };for (const p of s.trace) {if (!(p.v > 0.3) || !Number.isFinite(p.m) || p.t < tLeft) {- pen = false;+ flush();continue;}- const px = x(p.t), py = y(p.m);- if (pen) ctx.lineTo(px, py);- else ctx.moveTo(px, py);- pen = true;+ run.push([x(p.t), y(p.m)]);}- ctx.stroke();+ flush();+// now- ctx.fillStyle = C.caliperDim;- ctx.fillRect(Math.round(w * NOW_AT) - 0.5, 0, 1, h);+ const xn = left + (w - left) * NOW_AT;+ seg(ctx, xn, top, xn, h, V.white, 1, { dash: [3, 4], alpha: 0.6 });});return <canvas ref={ref} className="instrument-canvas roll-canvas" aria-label="Piano roll: the notes played, their syllables, and the pitch actually sung" />;}diff --git a/src/ui/components/SingPanel.tsx b/src/ui/components/SingPanel.tsxindex c1a0235..0bda411 100644--- a/src/ui/components/SingPanel.tsx+++ b/src/ui/components/SingPanel.tsx@@ -1,12 +1,33 @@import { useStore } from "../store.ts";import { useSing, playDemo, stopSinging, DEMO_SONGS } from "../singing.ts";-import { Slider, Toggle } from "./Controls.tsx";import { Keys } from "./Keys.tsx";import { PianoRoll } from "./PianoRoll.tsx";+import { SpectrumView } from "./SpectrumView.tsx";+import { Chip, Screen } from "./Screen.tsx";+import { EncoderPages } from "./Encoder.tsx";+import { noteName } from "./VoiceControls.tsx";+import type { InfoFn } from "./AnatomyView.tsx";/** epilarynx narrowing for the singer's ring (measured: +3 to +12 dB at 2.4–3.6 kHz, adult male) */const RING = 0.85;+/** the syllable being sung now: the demo's, or the one the held key sang */+function syllableNow(): string | null {+ const s = useSing.getState();+ if (s.demo) return s.syllables[s.demoAt]?.text ?? null;+ return useStore.getState().heldNotes.length ? (s.syllables[s.cursor - 1]?.text ?? null) : null;+}++/** Sing mode's lines over the face: the note, the syllable, the ring */+export const singInfo: InfoFn = (_m, _f, tele) => {+ const out: string[] = [];+ if (tele && tele.t.voicing > 0.3) out.push(`Note ${noteName(tele.t.f0)} ${tele.t.f0.toFixed(0)} Hz`);+ const syl = syllableNow();+ if (syl) out.push(`Syllable ${syl}`);+ out.push(useStore.getState().artic.epilarynx >= RING - 0.05 ? "Ring on" : "Ring off");+ return out;+};+function Lyrics() {const lyrics = useSing((s) => s.lyrics);const syllables = useSing((s) => s.syllables);@@ -16,22 +37,23 @@ function Lyrics() {const setLyrics = useSing((s) => s.setLyrics);const setCursor = useSing((s) => s.setCursor);const at = demo ? demoAt : -1;+ const done = demo ? demoAt : cursor;return (- <div className="panel lyrics-panel">- <h2>Lyrics</h2>+ <div className="lyrics"><textareavalue={lyrics}onChange={(e) => setLyrics(e.target.value)}onKeyDown={(e) => e.stopPropagation()}- rows={2}+ rows={1}aria-label="Lyrics to sing"placeholder="Type the words to sing"+ title="Each note sings the next syllable. Hold a key while you press the next one to sing legato. A lone “-” between words holds a vowel over several notes; hyphens split a word your way (“ti-ger”)."/><div className="syllables" role="group" aria-label="Syllables. Each note sings the marked one; choose another to start there.">{syllables.map((s, i) => (<span key={i} className={`syl-wrap${s.wordEnd ? " word-end" : ""}`}><button- className={`syl${!demo && i === cursor ? " next" : ""}${i === at ? " now" : ""}${s.melisma ? " held" : ""}`}+ className={`syl${!demo && i === cursor ? " next" : ""}${i === at ? " now" : ""}${i < done ? " sung" : ""}${s.melisma ? " held" : ""}`}onClick={() => setCursor(i)}aria-current={!demo && i === cursor ? "step" : undefined}title={s.melisma ? "Held vowel: carries the previous syllable onto this note" : `Sing from “${s.text}”`}@@ -46,74 +68,86 @@ function Lyrics() {</span>))}{!syllables.length && <span className="dim">No words: the keys sing “ah”.</span>}+ <Chip toggle={false} className="from-start" onClick={() => setCursor(0)} disabled={cursor === 0 && !demo}>+ From the start+ </Chip></div>- <div className="row">- <button className="ghost" onClick={() => setCursor(0)} disabled={cursor === 0 && !demo}>- Back to the first syllable- </button>- </div>- <p className="dim">- Each note sings the next syllable. Hold a key while you press the next one to sing legato. A lone “-” between words holds a vowel over several notes; hyphens split a word your way (“ti-ger”).- </p></div>);}-function SongAndVoice() {- const body = useStore((s) => s.body);- const start = useStore((s) => s.start);+function SongControls() {const source = useStore((s) => s.source);const setSource = useStore((s) => s.setSource);const epilarynx = useStore((s) => s.artic.epilarynx);const setArtic = useStore((s) => s.setArtic);- const demo = useSing((s) => s.demo);const vibrato = useSing((s) => s.vibrato);const setVibrato = useSing((s) => s.setVibrato);return (- <div className="panel song-panel">- <h2>Songs</h2>- <div className="examples" role="group" aria-label="Demo songs">- {DEMO_SONGS.map((s) => (- <button- key={s.name}- className={`chip${demo === s.name ? " on" : ""}`}- aria-pressed={demo === s.name}- onClick={async () => {- if (demo === s.name) {- stopSinging();- return;- }- await playDemo(s.name, body, start);- }}- >- {demo === s.name ? `Stop “${s.name}”` : s.name}- </button>- ))}- </div>- <h2>Voice</h2>- <Slider label="Vibrato depth" value={vibrato} min={0} max={80} onChange={(v) => setVibrato(Math.round(v))} format={(v) => `${Math.round(v)} cents`} />- <Slider label="Vibrato rate" value={source.vibratoRate} min={3.5} max={7.5} onChange={(v) => setSource({ vibratoRate: v })} format={(v) => `${v.toFixed(1)} Hz`} />- <Slider label="Breathiness" value={source.breathiness} min={0} max={1} onChange={(v) => setSource({ breathiness: v })} format={(v) => `${Math.round(v * 100)} %`} />- <Toggle label="Singer’s ring" checked={epilarynx >= RING - 0.05} onChange={(on) => setArtic({ epilarynx: on ? RING : 0 })} />- <p className="dim">Narrows the tube just above the vocal folds, adding the bright ring near 3 kHz that lets an opera voice carry.</p>+ <EncoderPages+ label="Song voice"+ pages={[+ {+ name: "Song",+ encoders: [+ { label: "Vibrato", value: vibrato, min: 0, max: 80, onChange: (v) => setVibrato(Math.round(v)), format: (v) => ({ value: String(Math.round(v)), unit: "cents" }) },+ { label: "Rate", value: source.vibratoRate, min: 3.5, max: 7.5, onChange: (v) => setSource({ vibratoRate: v }), format: (v) => ({ value: v.toFixed(1), unit: "Hz" }) },+ { label: "Breathy", value: source.breathiness, min: 0, max: 1, onChange: (v) => setSource({ breathiness: v }), format: (v) => ({ value: String(Math.round(v * 100)), unit: "%" }) },+ // the singer's ring narrows the tube just above the folds, adding the bright band near 3 kHz+ { label: "Ring", value: epilarynx, min: 0, max: 1, onChange: (v) => setArtic({ epilarynx: v }), format: (v) => ({ value: String(Math.round(v * 100)), unit: "%" }) },+ ],+ },+ ]}+ />+ );+}++function DemoSongs() {+ const body = useStore((s) => s.body);+ const start = useStore((s) => s.start);+ const demo = useSing((s) => s.demo);+ return (+ <div className="demo-songs" role="group" aria-label="Demo songs">+ {DEMO_SONGS.map((s) => (+ <Chip+ key={s.name}+ on={demo === s.name}+ onClick={async () => {+ if (demo === s.name) {+ stopSinging();+ return;+ }+ await playDemo(s.name, body, start);+ }}+ >+ {demo === s.name ? `Stop “${s.name}”` : s.name}+ </Chip>+ ))}</div>);}-export function SingPanel() {+/** Sing mode's right column: the piano roll, the lyrics, the spectrum with the ring, the song voice, the keys. */+export function SingRight() {+ const ring = useStore((s) => s.artic.epilarynx >= RING - 0.05);+ const next = useSing((s) => (s.demo ? null : (s.syllables[s.cursor]?.text ?? null)));return (- <>- <section className="sing">+ <div className="right right-sing">+ <Screen className="s-roll" title="Piano roll" sub="Notes and the pitch sung">+ <PianoRoll />+ </Screen>+ <Screen className="s-lyrics" title="Lyrics" sub="Each note sings the next syllable" tools={<DemoSongs />}><Lyrics />- <SongAndVoice />- <figure className="instrument roll-panel">- <figcaption>Notes, and the pitch actually sung</figcaption>- <PianoRoll />- </figure>- </section>- <footer className="keys-bar">+ </Screen>+ <Screen className="s-spec" title="Spectrum" sub={ring ? "Ring on" : ""}>+ <SpectrumView ring={ring} />+ </Screen>+ <Screen className="s-voice" title="Voice">+ <SongControls />+ </Screen>+ <Screen className="s-keys" title="Keys" sub={next ? `Next: ${next}` : ""}><Keys />- </footer>- </>+ </Screen>+ </div>);}diff --git a/src/ui/styles.css b/src/ui/styles.cssindex 8ad6b3b..0ca1c78 100644--- a/src/ui/styles.css+++ b/src/ui/styles.css@@ -2215,3 +2215,139 @@ input[type="range"]::-moz-range-thumb {flex-direction: row;}}++/* ---------- Sing */+.right-sing {+ grid-template-columns: minmax(0, 342fr) minmax(0, 342fr);+ grid-template-rows: minmax(0, 320fr) minmax(0, 134fr) minmax(0, 206fr) minmax(0, 172fr);+ grid-template-areas: "roll roll" "lyrics lyrics" "spec voice" "keys keys";+}++.s-roll { grid-area: roll; }+.s-lyrics { grid-area: lyrics; }++.screen-body > .roll-canvas {+ height: 100%;+}++.demo-songs {+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+}++.demo-songs .chip {+ padding: 2px 8px;+ font-size: 9px;+}++.lyrics {+ position: absolute;+ inset: 0;+ padding: 6px 14px 10px;+ display: grid;+ grid-template-rows: auto minmax(0, 1fr);+ gap: 8px;+}++.lyrics textarea {+ height: 30px;+ resize: none;+ padding: 5px 10px;+ font-size: 13px;+}++.lyrics .syllables {+ display: flex;+ flex-wrap: wrap;+ align-content: flex-start;+ gap: 4px 0;+ overflow-y: auto;+}++.syl-wrap {+ display: inline-flex;+ align-items: center;+ margin-right: 3px;+}++.syl-wrap.word-end {+ margin-right: 10px;+}++.syl {+ appearance: none;+ background: transparent;+ border: 1px solid var(--frame);+ border-radius: 0;+ color: var(--blue-mid);+ padding: 2px 7px;+ font-family: var(--font);+ font-size: 10px;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ cursor: pointer;+}++.syl.sung {+ color: var(--blue-dim);+ border-color: rgba(19, 57, 84, 0.6);+}++.syl.held {+ font-style: normal;+ opacity: 0.8;+}++.syl.next {+ background: transparent;+ color: var(--green);+ border: 1px dashed var(--green);+ box-shadow: none;+}++.syl.now {+ background: rgba(91, 227, 129, 0.1);+ color: var(--green);+ border: 1px solid var(--green);+ box-shadow: 0 0 6px rgba(91, 227, 129, 0.45);+ text-shadow: 0 0 3px rgba(91, 227, 129, 0.6);+}++.breath-mark {+ color: var(--blue-mid);+ margin-left: 2px;+}++.from-start {+ margin-left: 6px;+ padding: 2px 7px;+ font-size: 9px;+}++.right-sing .enc-label {+ font-size: 9px;+}++@media (max-width: 1100px) {+ .right-sing {+ grid-template-rows: none;+ grid-template-areas: "roll roll" "lyrics lyrics" "spec voice" "keys keys";+ }+ .right-sing .screen-body {+ min-height: 190px;+ }+ .s-roll .screen-body {+ min-height: 280px;+ }+ .s-lyrics .screen-body {+ min-height: 130px;+ }+}++@media (max-width: 640px) {+ .right-sing {+ grid-template-columns: minmax(0, 1fr);+ grid-template-areas: "roll" "lyrics" "spec" "voice" "keys";+ }+}