/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / App.tsx
337 lines · 12.5 KBBlameHistoryRaw
1import { useEffect, useMemo, useState } from "react";
2import { RecordPanel } from "./components/RecordPanel.tsx";
3import { TearView } from "./components/TearView.tsx";
4import { CompareView } from "./components/CompareView.tsx";
5import { About } from "./components/About.tsx";
6import { readTheme } from "./components/CanvasPlot.tsx";
7import { DEFAULT_SETTINGS, detectSegment, energyBand } from "./analysis/analyze.ts";
8import type { CaptureInfo } from "./audio/recorder.ts";
9import { encodeWavFloat32 } from "./audio/wav.ts";
10import { deleteRecording, listRecordings, newId, saveRecording, updateMeta, type RecordingMeta } from "./storage/db.ts";
11import {
12 download,
13 durationColor,
14 fmtDate,
15 fmtSec,
16 forgetAudio,
17 getAudio,
18 loadSettings,
19 putAudio,
20 safeName,
21 sampleTitle,
22 sortSamples,
23 storeSettings,
24 tearDuration,
25} from "./model.ts";
26import type { AnalysisSettings } from "./analysis/analyze.ts";
28type Tab = "record" | "compare" | "about";
29const NEW = "new"; // selection value for the "new sample" page
31export function App() {
32 const [recs, setRecs] = useState<RecordingMeta[]>([]);
33 const [loaded, setLoaded] = useState(false);
34 const [selected, setSelected] = useState<string>(NEW);
35 const [rerecording, setRerecording] = useState<string | null>(null);
36 const [tab, setTab] = useState<Tab>("record");
37 const [settings, setSettingsState] = useState<AnalysisSettings>(loadSettings);
38 const [showSettings, setShowSettings] = useState(false);
40 useEffect(() => {
41 listRecordings().then((r) => {
42 setRecs(r);
43 setLoaded(true);
44 if (r.length) setSelected(sortSamples(r)[0].id);
45 });
46 navigator.storage?.persist?.().catch(() => {});
47 }, []);
49 const samples = useMemo(() => sortSamples(recs), [recs]);
51 const setSettings = (s: AnalysisSettings) => {
52 setSettingsState(s);
53 storeSettings(s);
54 };
56 // Ranges found automatically follow the energy band: re-detect them when it changes.
57 // Ranges set by hand are left alone.
58 const { energyLow, energyHigh } = settings;
59 useEffect(() => {
60 if (!loaded) return;
61 let live = true;
62 (async () => {
63 for (const m of recs) {
64 if (m.segmentManual || (m.detectBand?.lo === energyLow && m.detectBand?.hi === energyHigh)) continue;
65 const x = await getAudio(m.id);
66 if (!live) return;
67 const band = { lo: energyLow, hi: energyHigh };
68 const updated = { ...m, segment: detectSegment(x, m.sampleRate, band), detectBand: band };
69 await updateMeta(updated);
70 setRecs((r) => r.map((q) => (q.id === m.id ? updated : q)));
71 }
72 })();
73 return () => {
74 live = false;
75 };
76 }, [loaded, recs, energyLow, energyHigh]);
78 // A new take: either a new sample, or a replacement for `replaces` (keeping its name and notes).
79 const onDone = async (replaces: RecordingMeta | null, x: Float32Array, fs: number, info: CaptureInfo | null, fileName?: string) => {
80 const band = energyBand(settings);
81 const meta: RecordingMeta = {
82 id: newId(),
83 createdAt: Date.now(),
84 label: replaces?.label ?? "",
85 notes: replaces?.notes ?? "",
86 material: "paper",
87 source: fileName ? "file" : "mic",
88 fileName,
89 sampleRate: fs,
90 length: x.length,
91 segment: detectSegment(x, fs, band),
92 segmentManual: false,
93 detectBand: band,
94 capture: info ?? undefined,
95 };
96 await saveRecording(meta, x);
97 putAudio(meta.id, x);
98 if (replaces) {
99 await deleteRecording(replaces.id);
100 forgetAudio(replaces.id);
101 }
102 setRecs((r) => [...r.filter((m) => m.id !== replaces?.id), meta]);
103 setRerecording(null);
104 setSelected(meta.id);
105 };
107 const onUpdate = async (meta: RecordingMeta) => {
108 await updateMeta(meta);
109 setRecs((r) => r.map((m) => (m.id === meta.id ? meta : m)));
110 };
112 const remove = async (m: RecordingMeta) => {
113 if (!confirm(`Delete this sample (${sampleTitle(m)})? This cannot be undone.`)) return;
114 await deleteRecording(m.id);
115 forgetAudio(m.id);
116 const rest = samples.filter((q) => q.id !== m.id);
117 setRecs((r) => r.filter((q) => q.id !== m.id));
118 setSelected(rest.length ? rest[Math.min(samples.indexOf(m), rest.length - 1)].id : NEW);
119 };
121 const current = recs.find((r) => r.id === selected) ?? null;
122 const th = readTheme(document.documentElement);
123 const dur = current ? tearDuration(current) : null;
125 return (
126 <div className="app">
127 <header className="topbar">
128 <h1>Rip Sound Analyzer</h1>
129 <nav className="tabs" role="tablist">
130 {(
131 [
132 ["record", "Record"],
133 ["compare", `Compare (${samples.length})`],
134 ["about", "What this can tell you"],
135 ] as [Tab, string][]
136 ).map(([t, name]) => (
137 <button key={t} role="tab" aria-selected={tab === t} className={tab === t ? "on" : ""} onClick={() => setTab(t)}>
138 {name}
139 </button>
140 ))}
141 </nav>
142 <button className="settings-btn" onClick={() => setShowSettings((s) => !s)} aria-expanded={showSettings}>
143 Analysis settings
144 </button>
145 </header>
147 {showSettings && <SettingsPanel settings={settings} setSettings={setSettings} />}
149 {tab === "record" && (
150 <div className="layout">
151 <aside className="sidebar" aria-label="Samples">
152 <div className="side-head">
153 Samples <span className="muted">slowest first</span>
154 </div>
155 <button
156 className={`speed-item new-item ${selected === NEW ? "sel" : ""}`}
157 onClick={() => {
158 setSelected(NEW);
159 setRerecording(null);
160 }}
161 >
162 <span className="plus">+</span>
163 <span className="speed-name">New sample</span>
164 </button>
165 {samples.map((m) => {
166 const d = tearDuration(m);
167 return (
168 <button
169 key={m.id}
170 className={`speed-item ${m.id === selected ? "sel" : ""}`}
171 onClick={() => {
172 setSelected(m.id);
173 setRerecording(null);
174 }}
175 >
176 <span className="dot done" style={{ background: durationColor(d, th) }} />
177 <span className="speed-text">
178 <span className="speed-name">
179 {sampleTitle(m)}
180 {d !== null && <span className="muted"> · {(settings.sheetLengthIn / d).toFixed(1)} in/s</span>}
181 </span>
182 <span className="muted small">{m.label || fmtDate(m.createdAt)}</span>
183 </span>
184 </button>
185 );
186 })}
187 {loaded && !samples.length && <p className="muted pad small">No samples yet.</p>}
188 <p className="muted pad small">Recordings are stored only in this browser.</p>
189 </aside>
191 <main className="main">
192 {selected === NEW || !current ? (
193 <>
194 <div className="speed-head">
195 <div>
196 <h2>New sample</h2>
197 <div className="muted small">Record a tear at any speed. It is added to the list when you stop.</div>
198 </div>
199 </div>
200 {loaded && <RecordPanel key="new" replacing={false} onDone={(x, fs, info, fileName) => onDone(null, x, fs, info, fileName)} onCancel={null} />}
201 </>
202 ) : (
203 <>
204 <div className="speed-head">
205 <div>
206 <h2>
207 {sampleTitle(current)}
208 {dur !== null && <span className="muted"> · {(settings.sheetLengthIn / dur).toFixed(2)} in/s</span>}
209 </h2>
210 <div className="muted small">
211 Recorded {fmtDate(current.createdAt)} · {fmtSec(current.length / current.sampleRate)} long
212 {current.fileName ? ` · from ${current.fileName}` : ""}
213 </div>
214 </div>
215 {rerecording !== current.id && (
216 <div className="toolbar">
217 <button onClick={() => setRerecording(current.id)}>Re-record</button>
218 <button
219 onClick={async () => {
220 const x = await getAudio(current.id);
221 const stamp = new Date(current.createdAt).toISOString().slice(0, 19).replace(/:/g, "-");
222 download(encodeWavFloat32(x, current.sampleRate), `tear_${stamp}${current.label ? "_" + safeName(current.label) : ""}.wav`);
223 }}
224 >
225 Download WAV
226 </button>
227 <button className="danger" onClick={() => remove(current)}>
228 Delete
229 </button>
230 </div>
231 )}
232 </div>
233 <NameField key={current.id} meta={current} onUpdate={onUpdate} />
235 {rerecording === current.id ? (
236 <RecordPanel
237 key={`re-${current.id}`}
238 replacing
239 onDone={(x, fs, info, fileName) => onDone(current, x, fs, info, fileName)}
240 onCancel={() => setRerecording(null)}
241 />
242 ) : (
243 <TearView key={current.id} meta={current} settings={settings} onUpdate={onUpdate} />
244 )}
245 </>
246 )}
247 </main>
248 </div>
249 )}
251 {tab === "compare" && (
252 <main className="main solo">
253 <CompareView
254 recs={samples}
255 settings={settings}
256 onOpen={(id) => {
257 setSelected(id);
258 setRerecording(null);
259 setTab("record");
260 }}
261 />
262 </main>
263 )}
264 {tab === "about" && (
265 <main className="main solo">
266 <About settings={settings} />
267 </main>
268 )}
269 </div>
270 );
273// Optional free-text name and notes for a sample.
274function NameField({ meta, onUpdate }: { meta: RecordingMeta; onUpdate: (m: RecordingMeta) => void }) {
275 const [label, setLabel] = useState(meta.label);
276 const [notes, setNotes] = useState(meta.notes);
277 return (
278 <div className="name-row">
279 <input
280 value={label}
281 placeholder="Name (optional)"
282 onChange={(e) => setLabel(e.target.value)}
283 onBlur={() => label !== meta.label && onUpdate({ ...meta, label: label.trim() })}
284 onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
285 aria-label="Sample name"
286 />
287 <input
288 className="notes-input"
289 value={notes}
290 placeholder="Notes (paper, how it was torn, anything unusual)"
291 onChange={(e) => setNotes(e.target.value)}
292 onBlur={() => notes !== meta.notes && onUpdate({ ...meta, notes })}
293 onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
294 aria-label="Notes"
295 />
296 </div>
297 );
300function SettingsPanel({ settings, setSettings }: { settings: AnalysisSettings; setSettings: (s: AnalysisSettings) => void }) {
301 const [d, setD] = useState(settings);
302 const changed = JSON.stringify(d) !== JSON.stringify(settings);
303 const field = (k: keyof AnalysisSettings, label: string, unit: string) => (
304 <label>
305 {label}
306 <input type="number" value={d[k]} min={0} onChange={(e) => setD({ ...d, [k]: +e.target.value })} />
307 {unit}
308 </label>
309 );
310 return (
311 <div className="settings card">
312 <div className="settings-row">
313 <b>Energy band</b>
314 {field("energyLow", "from", "Hz")}
315 {field("energyHigh", "to", "Hz")}
316 <span className="muted small">Used for total energy, finding the tear, the level-over-time plot and the background comparison.</span>
317 </div>
318 <div className="settings-row">
319 <b>Spectrum band</b>
320 {field("shapeLow", "from", "Hz")}
321 {field("shapeHigh", "to", "Hz")}
322 <span className="muted small">The frequency range shown when comparing spectra.</span>
323 </div>
324 <div className="settings-row">
325 {field("sheetLengthIn", "Tear length", "in")}
326 <button
327 className="primary"
328 disabled={!changed || d.energyHigh <= d.energyLow || d.shapeHigh <= d.shapeLow || d.sheetLengthIn <= 0}
329 onClick={() => setSettings(d)}
330 >
331 Apply
332 </button>
333 <button onClick={() => setD({ ...DEFAULT_SETTINGS })}>Defaults</button>
334 </div>
335 </div>
336 );
↑↓ move↵openescclose