d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 1import { useEffect, useMemo, useState } from "react";
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 2import { RecordPanel } from "./components/RecordPanel.tsx";
3import { TearView } from "./components/TearView.tsx";
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 4import { CompareView } from "./components/CompareView.tsx";
5import { About } from "./components/About.tsx";
6import { readTheme } from "./components/CanvasPlot.tsx";
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 7import { DEFAULT_SETTINGS, detectSegment, energyBand } from "./analysis/analyze.ts";
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 8import type { CaptureInfo } from "./audio/recorder.ts";
9import { encodeWavFloat32 } from "./audio/wav.ts";
bf56870Export/import the whole dataset; filtered waveform by defaultJeremy Magland 10import { exportDataset, readDataset } from "./storage/dataset.ts";
135ff3aAdd a button to clear all samples from the browserJeremy Magland 11import { clearAll, deleteRecording, listRecordings, newId, saveRecording, updateMeta, type RecordingMeta } from "./storage/db.ts";
13 download,
16 fmtSec,
19 getAudio,
20 loadSettings,
21 putAudio,
22 safeName,
24 sortSamples,
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 27} from "./model.ts";
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 28import type { AnalysisSettings } from "./analysis/analyze.ts";
30type Tab = "record" | "compare" | "about";
09371b0Open-ended samples instead of fixed speedsJeremy Magland 31const NEW = "new"; // selection value for the "new sample" page
33export function App() {
34 const [recs, setRecs] = useState<RecordingMeta[]>([]);
35 const [loaded, setLoaded] = useState(false);
09371b0Open-ended samples instead of fixed speedsJeremy Magland 36 const [selected, setSelected] = useState<string>(NEW);
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 37 const [rerecording, setRerecording] = useState<string | null>(null);
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 38 const [tab, setTab] = useState<Tab>("record");
39 const [settings, setSettingsState] = useState<AnalysisSettings>(loadSettings);
40 const [showSettings, setShowSettings] = useState(false);
42 useEffect(() => {
43 listRecordings().then((r) => {
44 setRecs(r);
45 setLoaded(true);
09371b0Open-ended samples instead of fixed speedsJeremy Magland 46 if (r.length) setSelected(sortSamples(r)[0].id);
48 navigator.storage?.persist?.().catch(() => {});
49 }, []);
09371b0Open-ended samples instead of fixed speedsJeremy Magland 51 const samples = useMemo(() => sortSamples(recs), [recs]);
53 const setSettings = (s: AnalysisSettings) => {
54 setSettingsState(s);
55 storeSettings(s);
56 };
751f8faSelect the tear on level, waveform or spectrogram; 10–20 kHz analysis bandJeremy Magland 58 // Ranges found automatically follow the analysis band: re-detect them when it changes.
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 59 // Ranges set by hand are left alone.
60 const { energyLow, energyHigh } = settings;
61 useEffect(() => {
62 if (!loaded) return;
63 let live = true;
64 (async () => {
65 for (const m of recs) {
09371b0Open-ended samples instead of fixed speedsJeremy Magland 66 if (m.segmentManual || (m.detectBand?.lo === energyLow && m.detectBand?.hi === energyHigh)) continue;
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 67 const x = await getAudio(m.id);
68 if (!live) return;
69 const band = { lo: energyLow, hi: energyHigh };
70 const updated = { ...m, segment: detectSegment(x, m.sampleRate, band), detectBand: band };
71 await updateMeta(updated);
72 setRecs((r) => r.map((q) => (q.id === m.id ? updated : q)));
73 }
74 })();
75 return () => {
76 live = false;
77 };
78 }, [loaded, recs, energyLow, energyHigh]);
09371b0Open-ended samples instead of fixed speedsJeremy Magland 80 // A new take: either a new sample, or a replacement for `replaces` (keeping its name and notes).
81 const onDone = async (replaces: RecordingMeta | null, x: Float32Array, fs: number, info: CaptureInfo | null, fileName?: string) => {
82 const band = energyBand(settings);
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 83 const meta: RecordingMeta = {
84 id: newId(),
85 createdAt: Date.now(),
87 notes: replaces?.notes ?? "",
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 88 material: "paper",
89 source: fileName ? "file" : "mic",
90 fileName,
91 sampleRate: fs,
92 length: x.length,
09371b0Open-ended samples instead of fixed speedsJeremy Magland 93 segment: detectSegment(x, fs, band),
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 94 segmentManual: false,
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 96 capture: info ?? undefined,
97 };
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 98 await saveRecording(meta, x);
99 putAudio(meta.id, x);
101 await deleteRecording(replaces.id);
102 forgetAudio(replaces.id);
09371b0Open-ended samples instead of fixed speedsJeremy Magland 104 setRecs((r) => [...r.filter((m) => m.id !== replaces?.id), meta]);
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 105 setRerecording(null);
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 109 const onUpdate = async (meta: RecordingMeta) => {
110 await updateMeta(meta);
111 setRecs((r) => r.map((m) => (m.id === meta.id ? meta : m)));
112 };
09371b0Open-ended samples instead of fixed speedsJeremy Magland 114 const remove = async (m: RecordingMeta) => {
115 if (!confirm(`Delete this sample (${sampleTitle(m)})? This cannot be undone.`)) return;
116 await deleteRecording(m.id);
117 forgetAudio(m.id);
118 const rest = samples.filter((q) => q.id !== m.id);
119 setRecs((r) => r.filter((q) => q.id !== m.id));
120 setSelected(rest.length ? rest[Math.min(samples.indexOf(m), rest.length - 1)].id : NEW);
135ff3aAdd a button to clear all samples from the browserJeremy Magland 123 const clearEverything = async () => {
124 if (!samples.length) return;
125 if (!confirm(`Delete all ${samples.length} sample${samples.length > 1 ? "s" : ""} from this browser? This cannot be undone. Download WAVs first if you want to keep any.`)) return;
126 await clearAll();
127 forgetAllAudio();
128 setRecs([]);
129 setRerecording(null);
130 setSelected(NEW);
131 };
bf56870Export/import the whole dataset; filtered waveform by defaultJeremy Magland 133 const [busy, setBusy] = useState<string | null>(null);
135 const doExport = async () => {
136 setBusy("Exporting…");
137 try {
138 const blob = await exportDataset(samples, settings, getAudio);
139 download(blob, `rip-sound-dataset-${new Date().toISOString().slice(0, 10)}.zip`);
140 } catch (e) {
141 alert(`Export failed: ${(e as Error).message}`);
142 } finally {
143 setBusy(null);
144 }
145 };
147 const doImport = async (file: File | undefined) => {
148 if (!file) return;
149 setBusy("Reading…");
150 try {
151 const ds = await readDataset(file);
152 const n = ds.samples.length;
153 const when = ds.exportedAt ? ` (exported ${fmtDate(Date.parse(ds.exportedAt))})` : "";
154 const msg =
155 `Replace everything in this browser with “${file.name}”${when}?\n\n` +
156 `${samples.length} current sample${samples.length === 1 ? "" : "s"} will be deleted and ${n} sample${n === 1 ? "" : "s"} loaded from the file. ` +
157 "The analysis settings saved in the file will be restored too. This cannot be undone.";
158 if (!confirm(msg)) return;
159 setBusy("Importing…");
160 await clearAll();
161 forgetAllAudio();
162 for (const { meta, audio } of ds.samples) {
163 await saveRecording(meta, audio);
164 putAudio(meta.id, audio);
165 }
166 if (ds.settings) setSettings({ ...DEFAULT_SETTINGS, ...ds.settings });
167 const metas = ds.samples.map((d) => d.meta);
168 setRecs(metas);
169 setRerecording(null);
170 setSelected(metas.length ? sortSamples(metas)[0].id : NEW);
171 } catch (e) {
172 alert(`Could not import “${file.name}”: ${(e as Error).message}`);
173 } finally {
174 setBusy(null);
175 }
176 };
09371b0Open-ended samples instead of fixed speedsJeremy Magland 178 const current = recs.find((r) => r.id === selected) ?? null;
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 179 const th = readTheme(document.documentElement);
09371b0Open-ended samples instead of fixed speedsJeremy Magland 180 const dur = current ? tearDuration(current) : null;
182 return (
183 <div className="app">
184 <header className="topbar">
185 <h1>Rip Sound Analyzer</h1>
186 <nav className="tabs" role="tablist">
187 {(
188 [
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 189 ["record", "Record"],
09371b0Open-ended samples instead of fixed speedsJeremy Magland 190 ["compare", `Compare (${samples.length})`],
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 191 ["about", "What this can tell you"],
192 ] as [Tab, string][]
193 ).map(([t, name]) => (
194 <button key={t} role="tab" aria-selected={tab === t} className={tab === t ? "on" : ""} onClick={() => setTab(t)}>
195 {name}
196 </button>
197 ))}
198 </nav>
199 <button className="settings-btn" onClick={() => setShowSettings((s) => !s)} aria-expanded={showSettings}>
200 Analysis settings
201 </button>
202 </header>
204 {showSettings && <SettingsPanel settings={settings} setSettings={setSettings} />}
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 206 {tab === "record" && (
207 <div className="layout">
09371b0Open-ended samples instead of fixed speedsJeremy Magland 208 <aside className="sidebar" aria-label="Samples">
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 209 <div className="side-head">
09371b0Open-ended samples instead of fixed speedsJeremy Magland 210 Samples <span className="muted">slowest first</span>
213 className={`speed-item new-item ${selected === NEW ? "sel" : ""}`}
214 onClick={() => {
215 setSelected(NEW);
216 setRerecording(null);
217 }}
218 >
219 <span className="plus">+</span>
220 <span className="speed-name">New sample</span>
221 </button>
222 {samples.map((m) => {
223 const d = tearDuration(m);
225 <button
227 className={`speed-item ${m.id === selected ? "sel" : ""}`}
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 228 onClick={() => {
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 230 setRerecording(null);
231 }}
232 >
09371b0Open-ended samples instead of fixed speedsJeremy Magland 233 <span className="dot done" style={{ background: durationColor(d, th) }} />
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 234 <span className="speed-text">
236 {sampleTitle(m)}
237 {d !== null && <span className="muted"> · {(settings.sheetLengthIn / d).toFixed(1)} in/s</span>}
09371b0Open-ended samples instead of fixed speedsJeremy Magland 239 <span className="muted small">{m.label || fmtDate(m.createdAt)}</span>
241 </button>
242 );
243 })}
09371b0Open-ended samples instead of fixed speedsJeremy Magland 244 {loaded && !samples.length && <p className="muted pad small">No samples yet.</p>}
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 245 <p className="muted pad small">Recordings are stored only in this browser.</p>
bf56870Export/import the whole dataset; filtered waveform by defaultJeremy Magland 246 <div className="data-actions pad">
247 <button onClick={doExport} disabled={!samples.length || !!busy} title="Save every sample and the analysis settings to one .zip file">
248 Export dataset
249 </button>
250 <label className={`button-like ${busy ? "disabled" : ""}`} title="Replace everything in this browser with a dataset file">
251 Import dataset…
252 <input
253 type="file"
254 accept=".zip,application/zip"
255 disabled={!!busy}
256 onChange={(e) => {
257 void doImport(e.target.files?.[0]);
258 e.target.value = "";
259 }}
260 />
261 </label>
262 {samples.length > 0 && (
263 <button className="danger" onClick={clearEverything} disabled={!!busy}>
265 </button>
267 {busy && <span className="muted small">{busy}</span>}
268 </div>
271 <main className="main">
09371b0Open-ended samples instead of fixed speedsJeremy Magland 272 {selected === NEW || !current ? (
273 <>
274 <div className="speed-head">
275 <div>
276 <h2>New sample</h2>
277 <div className="muted small">Record a tear at any speed. It is added to the list when you stop.</div>
278 </div>
09371b0Open-ended samples instead of fixed speedsJeremy Magland 280 {loaded && <RecordPanel key="new" replacing={false} onDone={(x, fs, info, fileName) => onDone(null, x, fs, info, fileName)} onCancel={null} />}
281 </>
282 ) : (
283 <>
284 <div className="speed-head">
285 <div>
286 <h2>
287 {sampleTitle(current)}
288 {dur !== null && <span className="muted"> · {(settings.sheetLengthIn / dur).toFixed(2)} in/s</span>}
289 </h2>
290 <div className="muted small">
291 Recorded {fmtDate(current.createdAt)} · {fmtSec(current.length / current.sampleRate)} long
292 {current.fileName ? ` · from ${current.fileName}` : ""}
293 </div>
294 </div>
295 {rerecording !== current.id && (
296 <div className="toolbar">
297 <button onClick={() => setRerecording(current.id)}>Re-record</button>
298 <button
299 onClick={async () => {
300 const x = await getAudio(current.id);
301 const stamp = new Date(current.createdAt).toISOString().slice(0, 19).replace(/:/g, "-");
302 download(encodeWavFloat32(x, current.sampleRate), `tear_${stamp}${current.label ? "_" + safeName(current.label) : ""}.wav`);
303 }}
304 >
305 Download WAV
306 </button>
307 <button className="danger" onClick={() => remove(current)}>
308 Delete
309 </button>
310 </div>
312 </div>
09371b0Open-ended samples instead of fixed speedsJeremy Magland 313 <NameField key={current.id} meta={current} onUpdate={onUpdate} />
316 <RecordPanel
317 key={`re-${current.id}`}
318 replacing
319 onDone={(x, fs, info, fileName) => onDone(current, x, fs, info, fileName)}
320 onCancel={() => setRerecording(null)}
321 />
322 ) : (
323 <TearView key={current.id} meta={current} settings={settings} onUpdate={onUpdate} />
324 )}
325 </>
327 </main>
328 </div>
329 )}
331 {tab === "compare" && (
332 <main className="main solo">
333 <CompareView
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 335 settings={settings}
336 onOpen={(id) => {
338 setRerecording(null);
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 339 setTab("record");
340 }}
341 />
342 </main>
343 )}
344 {tab === "about" && (
345 <main className="main solo">
346 <About settings={settings} />
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 347 </main>
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 349 </div>
350 );
351}
09371b0Open-ended samples instead of fixed speedsJeremy Magland 353// Optional free-text name and notes for a sample.
354function NameField({ meta, onUpdate }: { meta: RecordingMeta; onUpdate: (m: RecordingMeta) => void }) {
355 const [label, setLabel] = useState(meta.label);
356 const [notes, setNotes] = useState(meta.notes);
357 return (
358 <div className="name-row">
359 <input
360 value={label}
361 placeholder="Name (optional)"
362 onChange={(e) => setLabel(e.target.value)}
363 onBlur={() => label !== meta.label && onUpdate({ ...meta, label: label.trim() })}
364 onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
365 aria-label="Sample name"
366 />
367 <input
368 className="notes-input"
369 value={notes}
370 placeholder="Notes (paper, how it was torn, anything unusual)"
371 onChange={(e) => setNotes(e.target.value)}
372 onBlur={() => notes !== meta.notes && onUpdate({ ...meta, notes })}
373 onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
374 aria-label="Notes"
375 />
376 </div>
377 );
378}
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 380function SettingsPanel({ settings, setSettings }: { settings: AnalysisSettings; setSettings: (s: AnalysisSettings) => void }) {
381 const [d, setD] = useState(settings);
382 const changed = JSON.stringify(d) !== JSON.stringify(settings);
383 const field = (k: keyof AnalysisSettings, label: string, unit: string) => (
384 <label>
385 {label}
386 <input type="number" value={d[k]} min={0} onChange={(e) => setD({ ...d, [k]: +e.target.value })} />
387 {unit}
388 </label>
389 );
390 return (
391 <div className="settings card">
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 392 <div className="settings-row">
751f8faSelect the tear on level, waveform or spectrogram; 10–20 kHz analysis bandJeremy Magland 393 <b>Analysis band</b>
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 394 {field("energyLow", "from", "Hz")}
395 {field("energyHigh", "to", "Hz")}
751f8faSelect the tear on level, waveform or spectrogram; 10–20 kHz analysis bandJeremy Magland 396 <span className="muted small">Used for total energy, finding the tear, the level plot, the filtered waveform and the background comparison.</span>
398 <div className="settings-row">
399 {field("sheetLengthIn", "Tear length", "in")}
400 <button
401 className="primary"
751f8faSelect the tear on level, waveform or spectrogram; 10–20 kHz analysis bandJeremy Magland 402 disabled={!changed || d.energyHigh <= d.energyLow || d.sheetLengthIn <= 0}
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 403 onClick={() => setSettings(d)}
404 >
405 Apply
406 </button>
407 <button onClick={() => setD({ ...DEFAULT_SETTINGS })}>Defaults</button>
408 </div>
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 409 </div>
410 );
411}