d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 1import { useEffect, useRef, useState } from "react";
2import { MicRecorder, listInputs, type CaptureInfo } from "../audio/recorder.ts";
3import { decodeWav } from "../audio/wav.ts";
4import { syntheticTear } from "../audio/synthetic.ts";
5import { detectSegment } from "../analysis/analyze.ts";
6import { newId, type RecordingMeta } from "../storage/db.ts";
7import { PRESET_LABELS } from "../model.ts";
9const MAX_SECONDS = 60;
11interface Props {
12 label: string;
13 setLabel: (l: string) => void;
14 knownLabels: string[];
15 onNew: (meta: RecordingMeta, samples: Float32Array) => Promise<void>;
16}
18type Status = "closed" | "opening" | "ready" | "recording" | "saving";
20export function RecordBar({ label, setLabel, knownLabels, onNew }: Props) {
21 const rec = useRef<MicRecorder>(null);
22 rec.current ??= new MicRecorder();
23 const [status, setStatus] = useState<Status>("closed");
24 const [info, setInfo] = useState<CaptureInfo | null>(null);
25 const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
26 const [deviceId, setDeviceId] = useState<string>("");
27 const [error, setError] = useState<string | null>(null);
28 const [level, setLevel] = useState(-120);
29 const [clipped, setClipped] = useState(false);
30 const [elapsed, setElapsed] = useState(0);
31 const [synthT, setSynthT] = useState(1);
32 const peakAcc = useRef(0);
33 const peakHold = useRef(0);
34 const startedAt = useRef(0);
35 const statusRef = useRef(status);
36 statusRef.current = status;
38 // meter: accumulate peaks from the worklet, repaint at display rate
39 useEffect(() => {
40 let raf = 0;
41 const tick = () => {
42 const p = peakAcc.current;
43 peakAcc.current = 0;
44 peakHold.current = Math.max(p, peakHold.current * 0.93);
45 setLevel(20 * Math.log10(Math.max(peakHold.current, 1e-6)));
46 if (statusRef.current === "recording") {
47 const t = (performance.now() - startedAt.current) / 1000;
48 setElapsed(t);
49 if (t > MAX_SECONDS) void stop();
50 }
51 raf = requestAnimationFrame(tick);
52 };
53 raf = requestAnimationFrame(tick);
54 return () => cancelAnimationFrame(raf);
55 // eslint-disable-next-line react-hooks/exhaustive-deps
56 }, []);
58 useEffect(() => () => void rec.current?.close(), []);
60 async function open(id?: string) {
61 setError(null);
62 setStatus("opening");
63 try {
64 const r = rec.current!;
65 r.onPeak = (p) => {
66 peakAcc.current = Math.max(peakAcc.current, p);
67 if (p >= 0.99 && r.recording) setClipped(true);
68 };
69 const inf = await r.open(id || undefined);
70 setInfo(inf);
71 setDevices(await listInputs());
72 const dev = (inf.trackSettings.deviceId as string) ?? "";
73 setDeviceId(dev);
74 setStatus("ready");
75 } catch (e) {
76 setError(`Could not open the microphone: ${(e as Error).message}`);
77 setStatus("closed");
78 }
79 }
81 function start() {
82 if (statusRef.current !== "ready") return;
83 setClipped(false);
84 setElapsed(0);
85 startedAt.current = performance.now();
86 rec.current!.start();
87 setStatus("recording");
88 }
90 async function stop() {
91 if (statusRef.current !== "recording") return;
92 setStatus("saving");
93 const r = rec.current!;
94 const x = await r.stop();
95 const fs = r.sampleRate;
96 if (x.length < fs * 0.5) {
97 setError("Recording was shorter than half a second and was discarded.");
98 setStatus("ready");
99 return;
100 }
101 const seg = detectSegment(x, fs);
102 const meta: RecordingMeta = {
103 id: newId(),
104 createdAt: Date.now(),
105 label: label.trim() || "unlabelled",
106 notes: "",
107 material: "paper",
108 source: "mic",
109 sampleRate: fs,
110 length: x.length,
111 segment: seg,
112 segmentManual: false,
113 capture: r.info ?? undefined,
114 };
115 await onNew(meta, x);
116 setStatus("ready");
117 }
119 // space bar toggles recording (ignored while typing)
120 useEffect(() => {
121 const onKey = (e: KeyboardEvent) => {
122 if (e.code !== "Space" || e.repeat) return;
123 const t = e.target as HTMLElement;
124 if (t.closest("input, textarea, select, button")) return;
125 if (statusRef.current === "ready") {
126 e.preventDefault();
127 start();
128 } else if (statusRef.current === "recording") {
129 e.preventDefault();
130 void stop();
131 }
132 };
133 window.addEventListener("keydown", onKey);
134 return () => window.removeEventListener("keydown", onKey);
135 });
137 async function importFiles(files: FileList | null) {
138 if (!files) return;
139 setError(null);
140 for (const f of Array.from(files)) {
141 const buf = await f.arrayBuffer();
142 let fs: number;
143 let x: Float32Array;
144 let note = "";
145 const d = decodeWav(buf);
146 if (d) {
147 fs = d.sampleRate;
148 x = d.samples;
149 if (d.channels > 1) note = `File had ${d.channels} channels; only the first is used.`;
150 } else {
151 // other formats: let the browser decode (this resamples to the context rate)
152 try {
153 const ctx = new OfflineAudioContext(1, 1, 48000);
154 const ab = await ctx.decodeAudioData(buf);
155 fs = ab.sampleRate;
156 x = ab.getChannelData(0).slice();
157 note = "Decoded by the browser (not WAV): may have been resampled or lossy-compressed.";
158 } catch {
159 setError(`Could not read ${f.name}.`);
160 continue;
161 }
162 }
163 const name = f.name.replace(/\.[^.]+$/, "");
164 await onNew(
165 {
166 id: newId(),
167 createdAt: Date.now(),
168 label: label.trim() || "unlabelled",
169 notes: note,
170 material: "paper",
171 source: "file",
172 fileName: f.name || name,
173 sampleRate: fs,
174 length: x.length,
175 segment: detectSegment(x, fs),
176 segmentManual: false,
177 },
178 x,
179 );
180 }
181 }
183 async function addSynthetic() {
184 const fs = 48000;
185 const x = syntheticTear({ tearSeconds: synthT, sampleRate: fs, seed: Math.floor(Math.random() * 1e9) });
186 await onNew(
187 {
188 id: newId(),
189 createdAt: Date.now(),
190 label: `synthetic ${synthT} s`,
191 notes: "Synthetic: 4000 identical-shape clicks with random times and amplitudes. Not a real recording.",
192 material: "synthetic",
193 source: "synthetic",
194 sampleRate: fs,
195 length: x.length,
196 segment: detectSegment(x, fs),
197 segmentManual: false,
198 },
199 x,
200 );
201 }
203 const s = info?.trackSettings ?? {};
204 const processingOn = ["echoCancellation", "noiseSuppression", "autoGainControl"].filter((k) => s[k] === true);
205 const meterPct = Math.max(0, Math.min(100, ((level + 60) / 60) * 100));
207 return (
208 <section className="card recordbar" aria-label="Record">
209 <div className="rb-row">
210 <div className="rb-label">
211 <label htmlFor="speed-label">Speed label for the next recording</label>
212 <div className="chips">
213 {PRESET_LABELS.map((l) => (
214 <button key={l} className={`chip ${l === label ? "on" : ""}`} onClick={() => setLabel(l)}>
215 {l}
216 </button>
217 ))}
218 </div>
219 <input
220 id="speed-label"
221 list="known-labels"
222 value={label}
223 onChange={(e) => setLabel(e.target.value)}
224 placeholder="or type your own label"
225 />
226 <datalist id="known-labels">
227 {knownLabels.map((l) => (
228 <option key={l} value={l} />
229 ))}
230 </datalist>
231 </div>
233 <div className="rb-controls">
234 {status === "closed" || status === "opening" ? (
235 <button className="primary big" onClick={() => open()} disabled={status === "opening"}>
236 {status === "opening" ? "Opening…" : "Enable microphone"}
237 </button>
238 ) : (
239 <>
240 <button
241 className={`primary big ${status === "recording" ? "recording" : ""}`}
242 onClick={() => (status === "recording" ? stop() : start())}
243 disabled={status === "saving"}
244 >
245 {status === "recording" ? `■ Stop ${elapsed.toFixed(1)} s` : status === "saving" ? "Saving…" : "● Record"}
246 </button>
247 <div className="hint">Space bar also starts / stops.</div>
248 <div className="meter" title="Peak level (dBFS)">
249 <div className="meter-fill" style={{ width: `${meterPct}%` }} />
250 <span className="meter-text">{level > -119 ? `${level.toFixed(0)} dBFS` : "–"}</span>
251 </div>
252 {clipped && <div className="warn">⚠ Clipping in this recording: energy will be underestimated. Move the paper further from the mic.</div>}
253 </>
254 )}
255 </div>
256 </div>
258 <p className="howto">
259 Press record, keep still for about a second, tear one strip off the full 11 inch sheet, keep still for another second, then stop.
260 Keep the paper at the same distance and position relative to the microphone every time.
261 </p>
263 {info && (
264 <div className="capture-info">
265 <span>
266 <b>{info.deviceLabel || "microphone"}</b>
267 </span>
268 {devices.length > 1 && (
269 <select value={deviceId} onChange={(e) => open(e.target.value)} disabled={status === "recording"} aria-label="Input device">
270 {devices.map((d) => (
271 <option key={d.deviceId} value={d.deviceId}>
272 {d.label || d.deviceId}
273 </option>
274 ))}
275 </select>
276 )}
277 <span>{info.contextSampleRate} Hz</span>
278 <span>{String(s.channelCount ?? "?")} ch</span>
279 {processingOn.length ? (
280 <span className="warn">⚠ Browser processing still on: {processingOn.join(", ")}</span>
281 ) : (
282 <span className="ok">Browser processing off (echo cancellation, noise suppression, auto gain)</span>
283 )}
284 {typeof s.sampleRate === "number" && s.sampleRate !== info.contextSampleRate && (
285 <span className="warn">⚠ Mic rate {String(s.sampleRate)} Hz ≠ capture rate: audio is being resampled</span>
286 )}
287 </div>
288 )}
289 {error && <div className="warn">{error}</div>}
291 <details className="more">
292 <summary>Import a file or add a synthetic test tear</summary>
293 <div className="more-body">
294 <label className="filepick">
295 Import WAV file(s) (labelled with the speed label above)
296 <input type="file" accept=".wav,audio/*" multiple onChange={(e) => importFiles(e.target.files)} />
297 </label>
298 <div className="synth">
299 <span>Synthetic tear (identical clicks, for checking the analysis):</span>
300 <select value={synthT} onChange={(e) => setSynthT(+e.target.value)} aria-label="Synthetic tear duration">
301 {[0.3, 1, 3, 10].map((t) => (
302 <option key={t} value={t}>
303 {t} s
304 </option>
305 ))}
306 </select>
307 <button onClick={addSynthetic}>Add</button>
308 </div>
309 </div>
310 </details>
311 </section>
312 );
313}