/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / audio / recorder.ts
151 lines · 4.7 KBBlameHistoryRaw
1// Raw microphone capture. Browser processing (echo cancellation, noise suppression,
2// automatic gain) is switched off and samples are taken straight from the audio graph
3// with an AudioWorklet, so nothing is compressed or resampled by us.
5export interface CaptureInfo {
6 deviceLabel: string;
7 trackSettings: Record<string, unknown>;
8 contextSampleRate: number;
9 userAgent: string;
12const WORKLET_SRC = `
13class Tap extends AudioWorkletProcessor {
14 constructor() {
15 super();
16 this.buf = new Float32Array(4096);
17 this.n = 0;
18 this.on = false;
19 this.port.onmessage = (e) => {
20 if (e.data === 'start') { this.on = true; this.n = 0; }
21 else if (e.data === 'stop') { this.flush(); this.on = false; this.port.postMessage({ done: true }); }
22 };
23 }
24 flush() {
25 if (this.n > 0) {
26 const out = this.buf.slice(0, this.n);
27 this.port.postMessage({ chunk: out }, [out.buffer]);
28 this.n = 0;
29 }
30 }
31 process(inputs) {
32 const ch = inputs[0] && inputs[0][0];
33 if (!ch) return true;
34 let peak = 0;
35 for (let i = 0; i < ch.length; i++) { const v = Math.abs(ch[i]); if (v > peak) peak = v; }
36 this.port.postMessage({ peak });
37 if (this.on) {
38 for (let i = 0; i < ch.length; i++) {
39 this.buf[this.n++] = ch[i];
40 if (this.n === this.buf.length) this.flush();
41 }
42 }
43 return true;
44 }
46registerProcessor('tap', Tap);
47`;
49export const RAW_CONSTRAINTS: MediaTrackConstraints = {
50 echoCancellation: false,
51 noiseSuppression: false,
52 autoGainControl: false,
53 channelCount: 1,
54};
56export class MicRecorder {
57 private ctx: AudioContext | null = null;
58 private stream: MediaStream | null = null;
59 private node: AudioWorkletNode | null = null;
60 private chunks: Float32Array[] = [];
61 private stopResolve: ((x: Float32Array) => void) | null = null;
62 onPeak: ((peak: number) => void) | null = null;
63 info: CaptureInfo | null = null;
64 recording = false;
66 async open(deviceId?: string): Promise<CaptureInfo> {
67 await this.close();
68 const stream = await navigator.mediaDevices.getUserMedia({
69 audio: { ...RAW_CONSTRAINTS, ...(deviceId ? { deviceId: { exact: deviceId } } : {}) },
70 });
71 const track = stream.getAudioTracks()[0];
72 const settings = track.getSettings() as Record<string, unknown>;
73 // run the graph at the microphone's own rate so the browser does not resample
74 const rate = typeof settings.sampleRate === "number" ? settings.sampleRate : undefined;
75 const ctx = new AudioContext(rate ? { sampleRate: rate } : {});
76 const url = URL.createObjectURL(new Blob([WORKLET_SRC], { type: "text/javascript" }));
77 await ctx.audioWorklet.addModule(url);
78 URL.revokeObjectURL(url);
79 const src = ctx.createMediaStreamSource(stream);
80 const node = new AudioWorkletNode(ctx, "tap", { numberOfInputs: 1, numberOfOutputs: 1, channelCount: 1, channelCountMode: "explicit" });
81 const mute = ctx.createGain();
82 mute.gain.value = 0;
83 src.connect(node).connect(mute).connect(ctx.destination);
84 node.port.onmessage = (e) => {
85 const d = e.data;
86 if (d.chunk) this.chunks.push(d.chunk);
87 else if (d.peak !== undefined) this.onPeak?.(d.peak);
88 else if (d.done) {
89 const total = this.chunks.reduce((s, c) => s + c.length, 0);
90 const out = new Float32Array(total);
91 let o = 0;
92 for (const c of this.chunks) {
93 out.set(c, o);
94 o += c.length;
95 }
96 this.chunks = [];
97 this.stopResolve?.(out);
98 this.stopResolve = null;
99 }
100 };
101 if (ctx.state !== "running") await ctx.resume();
102 this.ctx = ctx;
103 this.stream = stream;
104 this.node = node;
105 this.info = {
106 deviceLabel: track.label,
107 trackSettings: settings,
108 contextSampleRate: ctx.sampleRate,
109 userAgent: navigator.userAgent,
110 };
111 return this.info;
112 }
114 get sampleRate() {
115 return this.ctx?.sampleRate ?? 0;
116 }
118 get isOpen() {
119 return !!this.ctx;
120 }
122 start() {
123 if (!this.node) throw new Error("Microphone is not open");
124 this.chunks = [];
125 this.recording = true;
126 this.node.port.postMessage("start");
127 }
129 stop(): Promise<Float32Array> {
130 if (!this.node) return Promise.resolve(new Float32Array(0));
131 this.recording = false;
132 return new Promise((resolve) => {
133 this.stopResolve = resolve;
134 this.node!.port.postMessage("stop");
135 });
136 }
138 async close() {
139 this.stream?.getTracks().forEach((t) => t.stop());
140 if (this.ctx) await this.ctx.close();
141 this.ctx = null;
142 this.stream = null;
143 this.node = null;
144 this.recording = false;
145 }
148export async function listInputs(): Promise<MediaDeviceInfo[]> {
149 const all = await navigator.mediaDevices.enumerateDevices();
150 return all.filter((d) => d.kind === "audioinput");
↑↓ move↵openescclose