"use client"; import { useCallback, useEffect, useRef, useState } from "react"; // THE MICROPHONE for a recording (the post bench, the recording session): // its devices, the one chosen (remembered per browser), a live level, and a // MediaRecorder -- opus in webm (Chromium) or ogg (Firefox). Localhost is a // secure context, so getUserMedia works with no network beyond it. export const MIC_KEY = "umtool.post-narration.mic"; export const ls = { get: (k: string) => { try { return window.localStorage.getItem(k); } catch { return null; } }, set: (k: string, v: string) => { try { window.localStorage.setItem(k, v); } catch { // private mode: not remembered } }, }; /** The microphone: its devices, the one chosen (remembered), a level, a recorder. */ export function useMic() { const [devices, setDevices] = useState([]); const [device, setDevice] = useState(""); const [level, setLevel] = useState(0); const [error, setError] = useState(null); const stream = useRef(null); const rec = useRef(null); const chunks = useRef([]); const raf = useRef(0); const ctx = useRef(null); const open = useCallback(async (id?: string) => { setError(null); try { stream.current?.getTracks().forEach((t) => t.stop()); const s = await navigator.mediaDevices.getUserMedia({ audio: id ? { deviceId: { exact: id }, echoCancellation: false, noiseSuppression: false, autoGainControl: false } : { echoCancellation: false, noiseSuppression: false, autoGainControl: false } }); stream.current = s; const list = (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "audioinput"); setDevices(list); const now = s.getAudioTracks()[0]?.getSettings().deviceId ?? id ?? ""; setDevice(now); if (now) ls.set(MIC_KEY, now); ctx.current ??= new AudioContext(); const an = ctx.current.createAnalyser(); an.fftSize = 1024; ctx.current.createMediaStreamSource(s).connect(an); const buf = new Float32Array(an.fftSize); cancelAnimationFrame(raf.current); const tick = () => { an.getFloatTimeDomainData(buf); let acc = 0; for (const v of buf) acc += v * v; setLevel(Math.min(1, Math.sqrt(acc / buf.length) * 4)); raf.current = requestAnimationFrame(tick); }; tick(); return s; } catch (e) { setError(e instanceof Error ? e.message : String(e)); return null; } }, []); useEffect(() => () => { cancelAnimationFrame(raf.current); stream.current?.getTracks().forEach((t) => t.stop()); }, []); const start = useCallback(async () => { const s = stream.current ?? (await open(ls.get(MIC_KEY) ?? undefined)); if (!s) return false; chunks.current = []; const type = ["audio/webm;codecs=opus", "audio/ogg;codecs=opus", "audio/webm"].find((t) => typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(t)); const r = new MediaRecorder(s, type ? { mimeType: type } : undefined); r.ondataavailable = (ev) => ev.data.size && chunks.current.push(ev.data); r.start(250); rec.current = r; return true; }, [open]); const stop = useCallback( () => new Promise((resolve) => { const r = rec.current; if (!r || r.state === "inactive") return resolve(null); r.onstop = () => resolve(new Blob(chunks.current, { type: r.mimeType || "audio/webm" })); r.stop(); }), [], ); return { devices, device, level, error, open, start, stop }; }