import { useEffect, useRef, useState } from "react"; import { MicRecorder, listInputs, type CaptureInfo } from "../audio/recorder.ts"; import { decodeWav } from "../audio/wav.ts"; import { syntheticTear } from "../audio/synthetic.ts"; import { detectSegment } from "../analysis/analyze.ts"; import { newId, type RecordingMeta } from "../storage/db.ts"; import { PRESET_LABELS } from "../model.ts"; const MAX_SECONDS = 60; interface Props { label: string; setLabel: (l: string) => void; knownLabels: string[]; onNew: (meta: RecordingMeta, samples: Float32Array) => Promise; } type Status = "closed" | "opening" | "ready" | "recording" | "saving"; export function RecordBar({ label, setLabel, knownLabels, onNew }: Props) { const rec = useRef(null); rec.current ??= new MicRecorder(); const [status, setStatus] = useState("closed"); const [info, setInfo] = useState(null); const [devices, setDevices] = useState([]); const [deviceId, setDeviceId] = useState(""); const [error, setError] = useState(null); const [level, setLevel] = useState(-120); const [clipped, setClipped] = useState(false); const [elapsed, setElapsed] = useState(0); const [synthT, setSynthT] = useState(1); const peakAcc = useRef(0); const peakHold = useRef(0); const startedAt = useRef(0); const statusRef = useRef(status); statusRef.current = status; // meter: accumulate peaks from the worklet, repaint at display rate useEffect(() => { let raf = 0; const tick = () => { const p = peakAcc.current; peakAcc.current = 0; peakHold.current = Math.max(p, peakHold.current * 0.93); setLevel(20 * Math.log10(Math.max(peakHold.current, 1e-6))); if (statusRef.current === "recording") { const t = (performance.now() - startedAt.current) / 1000; setElapsed(t); if (t > MAX_SECONDS) void stop(); } raf = requestAnimationFrame(tick); }; raf = requestAnimationFrame(tick); return () => cancelAnimationFrame(raf); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => () => void rec.current?.close(), []); async function open(id?: string) { setError(null); setStatus("opening"); try { const r = rec.current!; r.onPeak = (p) => { peakAcc.current = Math.max(peakAcc.current, p); if (p >= 0.99 && r.recording) setClipped(true); }; const inf = await r.open(id || undefined); setInfo(inf); setDevices(await listInputs()); const dev = (inf.trackSettings.deviceId as string) ?? ""; setDeviceId(dev); setStatus("ready"); } catch (e) { setError(`Could not open the microphone: ${(e as Error).message}`); setStatus("closed"); } } function start() { if (statusRef.current !== "ready") return; setClipped(false); setElapsed(0); startedAt.current = performance.now(); rec.current!.start(); setStatus("recording"); } async function stop() { if (statusRef.current !== "recording") return; setStatus("saving"); const r = rec.current!; const x = await r.stop(); const fs = r.sampleRate; if (x.length < fs * 0.5) { setError("Recording was shorter than half a second and was discarded."); setStatus("ready"); return; } const seg = detectSegment(x, fs); const meta: RecordingMeta = { id: newId(), createdAt: Date.now(), label: label.trim() || "unlabelled", notes: "", material: "paper", source: "mic", sampleRate: fs, length: x.length, segment: seg, segmentManual: false, capture: r.info ?? undefined, }; await onNew(meta, x); setStatus("ready"); } // space bar toggles recording (ignored while typing) useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.code !== "Space" || e.repeat) return; const t = e.target as HTMLElement; if (t.closest("input, textarea, select, button")) return; if (statusRef.current === "ready") { e.preventDefault(); start(); } else if (statusRef.current === "recording") { e.preventDefault(); void stop(); } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }); async function importFiles(files: FileList | null) { if (!files) return; setError(null); for (const f of Array.from(files)) { const buf = await f.arrayBuffer(); let fs: number; let x: Float32Array; let note = ""; const d = decodeWav(buf); if (d) { fs = d.sampleRate; x = d.samples; if (d.channels > 1) note = `File had ${d.channels} channels; only the first is used.`; } else { // other formats: let the browser decode (this resamples to the context rate) try { const ctx = new OfflineAudioContext(1, 1, 48000); const ab = await ctx.decodeAudioData(buf); fs = ab.sampleRate; x = ab.getChannelData(0).slice(); note = "Decoded by the browser (not WAV): may have been resampled or lossy-compressed."; } catch { setError(`Could not read ${f.name}.`); continue; } } const name = f.name.replace(/\.[^.]+$/, ""); await onNew( { id: newId(), createdAt: Date.now(), label: label.trim() || "unlabelled", notes: note, material: "paper", source: "file", fileName: f.name || name, sampleRate: fs, length: x.length, segment: detectSegment(x, fs), segmentManual: false, }, x, ); } } async function addSynthetic() { const fs = 48000; const x = syntheticTear({ tearSeconds: synthT, sampleRate: fs, seed: Math.floor(Math.random() * 1e9) }); await onNew( { id: newId(), createdAt: Date.now(), label: `synthetic ${synthT} s`, notes: "Synthetic: 4000 identical-shape clicks with random times and amplitudes. Not a real recording.", material: "synthetic", source: "synthetic", sampleRate: fs, length: x.length, segment: detectSegment(x, fs), segmentManual: false, }, x, ); } const s = info?.trackSettings ?? {}; const processingOn = ["echoCancellation", "noiseSuppression", "autoGainControl"].filter((k) => s[k] === true); const meterPct = Math.max(0, Math.min(100, ((level + 60) / 60) * 100)); return (
{PRESET_LABELS.map((l) => ( ))}
setLabel(e.target.value)} placeholder="or type your own label" /> {knownLabels.map((l) => (
{status === "closed" || status === "opening" ? ( ) : ( <>
Space bar also starts / stops.
{level > -119 ? `${level.toFixed(0)} dBFS` : "–"}
{clipped &&
⚠ Clipping in this recording: energy will be underestimated. Move the paper further from the mic.
} )}

Press record, keep still for about a second, tear one strip off the full 11 inch sheet, keep still for another second, then stop. Keep the paper at the same distance and position relative to the microphone every time.

{info && (
{info.deviceLabel || "microphone"} {devices.length > 1 && ( )} {info.contextSampleRate} Hz {String(s.channelCount ?? "?")} ch {processingOn.length ? ( ⚠ Browser processing still on: {processingOn.join(", ")} ) : ( Browser processing off (echo cancellation, noise suppression, auto gain) )} {typeof s.sampleRate === "number" && s.sampleRate !== info.contextSampleRate && ( ⚠ Mic rate {String(s.sampleRate)} Hz ≠ capture rate: audio is being resampled )}
)} {error &&
{error}
}
Import a file or add a synthetic test tear
Synthetic tear (identical clicks, for checking the analysis):
); }