1import { useEffect } from "react";
2import { mic, useMic } from "../audio/mic.ts";
3import type { CaptureInfo } from "../audio/recorder.ts";
4import { decodeWav } from "../audio/wav.ts";
6const MAX_SECONDS = 60;
8interface Props {
9 replacing: boolean; // re-recording an existing sample
10 onDone: (samples: Float32Array, fs: number, info: CaptureInfo | null, fileName?: string) => Promise<void>;
11 onCancel: (() => void) | null;
12}
14export function RecordPanel({ replacing, onDone, onCancel }: Props) {
15 const m = useMic();
16 const elapsed = m.status === "recording" ? (performance.now() - m.startedAt) / 1000 : 0;
18 const stop = async () => {
19 const r = await mic.stop();
20 if (!r) return;
21 if (r.samples.length < r.fs * 0.5) {
22 alert("That recording was shorter than half a second and was not kept.");
23 return;
24 }
25 await onDone(r.samples, r.fs, r.info);
26 };
28 useEffect(() => {
29 if (m.status === "recording" && elapsed > MAX_SECONDS) void stop();
30 });
32 // space bar starts / stops (ignored while typing or when a button has focus)
33 useEffect(() => {
34 const onKey = (e: KeyboardEvent) => {
35 if (e.code !== "Space" || e.repeat) return;
36 if ((e.target as HTMLElement).closest("input, textarea, select, button")) return;
37 const st = mic.get().status;
38 if (st === "ready") {
39 e.preventDefault();
40 mic.start();
41 } else if (st === "recording") {
42 e.preventDefault();
43 void stop();
44 }
45 };
46 window.addEventListener("keydown", onKey);
47 return () => window.removeEventListener("keydown", onKey);
48 });
50 // leaving this panel mid-recording discards the take
51 useEffect(() => () => void mic.cancel(), []);
53 const loadFile = async (f: File | undefined) => {
54 if (!f) return;
55 const d = decodeWav(await f.arrayBuffer());
56 if (!d) {
57 alert("Only WAV files can be loaded.");
58 return;
59 }
60 await onDone(d.samples, d.sampleRate, null, f.name);
61 };
63 const s = m.info?.trackSettings ?? {};
64 const processingOn = ["echoCancellation", "noiseSuppression", "autoGainControl"].filter((k) => s[k] === true);
65 const levelDb = 20 * Math.log10(Math.max(m.peak, 1e-6));
66 const meterPct = Math.max(0, Math.min(100, ((levelDb + 60) / 60) * 100));
68 return (
69 <section className="card record-panel">
70 {replacing && (
71 <div className="replace-note">
72 Re-recording this sample. The current recording stays until you finish; the new one then replaces it.
73 </div>
74 )}
75 <ol className="steps">
76 <li>Press <b>Start</b> (or the space bar) and keep still for about a second.</li>
77 <li>
78 Tear one strip off the full 11 inch sheet, at whatever speed you want to study.
79 </li>
80 <li>Keep still for another second, then press <b>Stop</b>.</li>
81 </ol>
83 <div className="rec-controls">
84 {m.status === "closed" || m.status === "opening" ? (
85 <button className="primary big" onClick={() => mic.open()} disabled={m.status === "opening"}>
86 {m.status === "opening" ? "Opening…" : "Enable microphone"}
87 </button>
88 ) : m.status === "recording" ? (
89 <button className="primary big recording" onClick={stop}>
90 ■ Stop · {elapsed.toFixed(1)} s
91 </button>
92 ) : (
93 <button className="primary big" onClick={() => mic.start()} disabled={m.status === "saving"}>
94 {m.status === "saving" ? "Saving…" : "● Start"}
95 </button>
96 )}
97 {m.status !== "closed" && m.status !== "opening" && (
98 <div className="meter" title="Input peak level">
99 <div className="meter-fill" style={{ width: `${meterPct}%` }} />
100 <span className="meter-text">{levelDb > -119 ? `${levelDb.toFixed(0)} dBFS` : "–"}</span>
101 </div>
102 )}
103 {onCancel && (
104 <button onClick={() => (m.status === "recording" ? mic.cancel().then(onCancel) : onCancel())}>Cancel</button>
105 )}
106 </div>
107 {m.clipped && m.status === "recording" && (
108 <div className="warn">⚠ Clipping: the sound hit full scale, so its energy will be underestimated. Tear further from the microphone and re-record.</div>
109 )}
110 {m.error && <div className="warn">{m.error}</div>}
112 {m.info && (
113 <div className="capture-info">
114 <span>{m.info.deviceLabel || "Microphone"}</span>
115 {m.devices.length > 1 && (
116 <select
117 value={String(s.deviceId ?? "")}
118 onChange={(e) => mic.open(e.target.value)}
119 disabled={m.status === "recording"}
120 aria-label="Input device"
121 >
122 {m.devices.map((d) => (
123 <option key={d.deviceId} value={d.deviceId}>
124 {d.label || d.deviceId}
125 </option>
126 ))}
127 </select>
128 )}
129 <span>{m.info.contextSampleRate} Hz</span>
130 {processingOn.length ? (
131 <span className="warn">⚠ Browser processing still on: {processingOn.join(", ")}</span>
132 ) : (
133 <span className="ok">✓ Browser processing off</span>
134 )}
135 {typeof s.sampleRate === "number" && s.sampleRate !== m.info.contextSampleRate && (
136 <span className="warn">⚠ Audio is being resampled from {String(s.sampleRate)} Hz</span>
137 )}
138 </div>
139 )}
141 <label className="file-link">
142 or load a WAV file instead
143 <input type="file" accept=".wav,audio/wav" onChange={(e) => loadFile(e.target.files?.[0])} />
144 </label>
145 </section>
146 );
147}