1// One microphone for the whole app, opened once and kept open while switching speeds.
2import { useSyncExternalStore } from "react";
3import { MicRecorder, listInputs, type CaptureInfo } from "./recorder.ts";
5export interface MicState {
6 status: "closed" | "opening" | "ready" | "recording" | "saving";
7 info: CaptureInfo | null;
8 devices: MediaDeviceInfo[];
9 error: string | null;
10 peak: number; // latest peak (linear), decays for display
11 clipped: boolean; // during the current recording
12 startedAt: number; // performance.now() at start of recording
13}
15const rec = new MicRecorder();
16let state: MicState = { status: "closed", info: null, devices: [], error: null, peak: 0, clipped: false, startedAt: 0 };
17const listeners = new Set<() => void>();
18const set = (p: Partial<MicState>) => {
19 state = { ...state, ...p };
20 listeners.forEach((l) => l());
21};
23let peakAcc = 0;
24rec.onPeak = (p) => {
25 peakAcc = Math.max(peakAcc, p);
26 if (p >= 0.99 && rec.recording && !state.clipped) set({ clipped: true });
27};
28// repaint the meter at display rate rather than per audio block
29const tick = () => {
30 if (state.status !== "closed") {
31 const shown = Math.max(peakAcc, state.peak * 0.93);
32 peakAcc = 0;
33 if (Math.abs(shown - state.peak) > 1e-5 || state.status === "recording") set({ peak: shown });
34 }
35 requestAnimationFrame(tick);
36};
37requestAnimationFrame(tick);
39export const mic = {
40 get: () => state,
41 subscribe(l: () => void) {
42 listeners.add(l);
43 return () => listeners.delete(l);
44 },
45 get sampleRate() {
46 return rec.sampleRate;
47 },
48 async open(deviceId?: string) {
49 set({ status: "opening", error: null });
50 try {
51 const info = await rec.open(deviceId);
52 set({ status: "ready", info, devices: await listInputs() });
53 } catch (e) {
54 set({ status: "closed", error: `Could not open the microphone: ${(e as Error).message}` });
55 }
56 },
57 start() {
58 if (state.status !== "ready") return;
59 rec.start();
60 set({ status: "recording", clipped: false, startedAt: performance.now() });
61 },
62 async stop(): Promise<{ samples: Float32Array; fs: number; info: CaptureInfo | null } | null> {
63 if (state.status !== "recording") return null;
64 set({ status: "saving" });
65 const samples = await rec.stop();
66 set({ status: "ready" });
67 return { samples, fs: rec.sampleRate, info: rec.info };
68 },
69 async cancel() {
70 if (state.status !== "recording") return;
71 await rec.stop();
72 set({ status: "ready" });
73 },
74};
76export function useMic(): MicState {
77 return useSyncExternalStore(mic.subscribe, mic.get);
78}