/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / audio / synthetic.ts
64 lines · 2.2 KBBlameHistoryRaw
1// Synthetic "tears" built exactly as the hypothesis says: the same set of clicks
2// (same shape, same amplitude distribution, same count) placed at random times over
3// the tear duration. Useful for checking that the analysis behaves as expected:
4// energy and spectrum should not depend on duration.
6function mulberry32(seed: number) {
7 return () => {
8 seed |= 0;
9 seed = (seed + 0x6d2b79f5) | 0;
10 let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
11 t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
12 return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
13 };
16function gauss(rand: () => number) {
17 const u = Math.max(rand(), 1e-12);
18 return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * rand());
21export interface SyntheticOptions {
22 tearSeconds: number;
23 clicks?: number;
24 sampleRate?: number;
25 quietSeconds?: number; // before and after the tear
26 backgroundDbfs?: number;
27 seed?: number;
30export function syntheticTear(opts: SyntheticOptions): Float32Array {
31 const fs = opts.sampleRate ?? 48000;
32 const clicks = opts.clicks ?? 4000;
33 const quiet = opts.quietSeconds ?? 1;
34 const rand = mulberry32(opts.seed ?? 1);
36 // one fixed click template (same for every synthetic tear): decaying high-passed noise, ~1 ms
37 const tRand = mulberry32(12345);
38 const tl = Math.round(0.002 * fs);
39 const template = new Float32Array(tl);
40 let prev = 0;
41 for (let i = 0; i < tl; i++) {
42 const g = gauss(tRand);
43 template[i] = (g - prev) * Math.exp(-i / (0.00025 * fs));
44 prev = g;
45 }
46 let te = 0;
47 for (const v of template) te += v * v;
48 for (let i = 0; i < tl; i++) template[i] /= Math.sqrt(te);
50 const n = Math.round((2 * quiet + opts.tearSeconds) * fs);
51 const out = new Float32Array(n);
52 const bg = 10 ** ((opts.backgroundDbfs ?? -75) / 20);
53 for (let i = 0; i < n; i++) out[i] = bg * gauss(rand);
55 const start = quiet * fs;
56 const len = opts.tearSeconds * fs;
57 for (let c = 0; c < clicks; c++) {
58 const pos = Math.floor(start + rand() * (len - tl));
59 // log-normal amplitudes, random polarity
60 const amp = 0.02 * Math.exp(0.8 * gauss(rand)) * (rand() < 0.5 ? -1 : 1);
61 for (let i = 0; i < tl; i++) out[pos + i] += amp * template[i];
62 }
63 return out;
↑↓ move↵openescclose