// One microphone for the whole app, opened once and kept open while switching speeds. import { useSyncExternalStore } from "react"; import { MicRecorder, listInputs, type CaptureInfo } from "./recorder.ts"; export interface MicState { status: "closed" | "opening" | "ready" | "recording" | "saving"; info: CaptureInfo | null; devices: MediaDeviceInfo[]; error: string | null; peak: number; // latest peak (linear), decays for display clipped: boolean; // during the current recording startedAt: number; // performance.now() at start of recording } const rec = new MicRecorder(); let state: MicState = { status: "closed", info: null, devices: [], error: null, peak: 0, clipped: false, startedAt: 0 }; const listeners = new Set<() => void>(); const set = (p: Partial) => { state = { ...state, ...p }; listeners.forEach((l) => l()); }; let peakAcc = 0; rec.onPeak = (p) => { peakAcc = Math.max(peakAcc, p); if (p >= 0.99 && rec.recording && !state.clipped) set({ clipped: true }); }; // repaint the meter at display rate rather than per audio block const tick = () => { if (state.status !== "closed") { const shown = Math.max(peakAcc, state.peak * 0.93); peakAcc = 0; if (Math.abs(shown - state.peak) > 1e-5 || state.status === "recording") set({ peak: shown }); } requestAnimationFrame(tick); }; requestAnimationFrame(tick); export const mic = { get: () => state, subscribe(l: () => void) { listeners.add(l); return () => listeners.delete(l); }, get sampleRate() { return rec.sampleRate; }, async open(deviceId?: string) { set({ status: "opening", error: null }); try { const info = await rec.open(deviceId); set({ status: "ready", info, devices: await listInputs() }); } catch (e) { set({ status: "closed", error: `Could not open the microphone: ${(e as Error).message}` }); } }, start() { if (state.status !== "ready") return; rec.start(); set({ status: "recording", clipped: false, startedAt: performance.now() }); }, async stop(): Promise<{ samples: Float32Array; fs: number; info: CaptureInfo | null } | null> { if (state.status !== "recording") return null; set({ status: "saving" }); const samples = await rec.stop(); set({ status: "ready" }); return { samples, fs: rec.sampleRate, info: rec.info }; }, async cancel() { if (state.status !== "recording") return; await rec.stop(); set({ status: "ready" }); }, }; export function useMic(): MicState { return useSyncExternalStore(mic.subscribe, mic.get); }