// Raw microphone capture. Browser processing (echo cancellation, noise suppression, // automatic gain) is switched off and samples are taken straight from the audio graph // with an AudioWorklet, so nothing is compressed or resampled by us. export interface CaptureInfo { deviceLabel: string; trackSettings: Record; contextSampleRate: number; userAgent: string; } const WORKLET_SRC = ` class Tap extends AudioWorkletProcessor { constructor() { super(); this.buf = new Float32Array(4096); this.n = 0; this.on = false; this.port.onmessage = (e) => { if (e.data === 'start') { this.on = true; this.n = 0; } else if (e.data === 'stop') { this.flush(); this.on = false; this.port.postMessage({ done: true }); } }; } flush() { if (this.n > 0) { const out = this.buf.slice(0, this.n); this.port.postMessage({ chunk: out }, [out.buffer]); this.n = 0; } } process(inputs) { const ch = inputs[0] && inputs[0][0]; if (!ch) return true; let peak = 0; for (let i = 0; i < ch.length; i++) { const v = Math.abs(ch[i]); if (v > peak) peak = v; } this.port.postMessage({ peak }); if (this.on) { for (let i = 0; i < ch.length; i++) { this.buf[this.n++] = ch[i]; if (this.n === this.buf.length) this.flush(); } } return true; } } registerProcessor('tap', Tap); `; export const RAW_CONSTRAINTS: MediaTrackConstraints = { echoCancellation: false, noiseSuppression: false, autoGainControl: false, channelCount: 1, }; export class MicRecorder { private ctx: AudioContext | null = null; private stream: MediaStream | null = null; private node: AudioWorkletNode | null = null; private chunks: Float32Array[] = []; private stopResolve: ((x: Float32Array) => void) | null = null; onPeak: ((peak: number) => void) | null = null; info: CaptureInfo | null = null; recording = false; async open(deviceId?: string): Promise { await this.close(); const stream = await navigator.mediaDevices.getUserMedia({ audio: { ...RAW_CONSTRAINTS, ...(deviceId ? { deviceId: { exact: deviceId } } : {}) }, }); const track = stream.getAudioTracks()[0]; const settings = track.getSettings() as Record; // run the graph at the microphone's own rate so the browser does not resample const rate = typeof settings.sampleRate === "number" ? settings.sampleRate : undefined; const ctx = new AudioContext(rate ? { sampleRate: rate } : {}); const url = URL.createObjectURL(new Blob([WORKLET_SRC], { type: "text/javascript" })); await ctx.audioWorklet.addModule(url); URL.revokeObjectURL(url); const src = ctx.createMediaStreamSource(stream); const node = new AudioWorkletNode(ctx, "tap", { numberOfInputs: 1, numberOfOutputs: 1, channelCount: 1, channelCountMode: "explicit" }); const mute = ctx.createGain(); mute.gain.value = 0; src.connect(node).connect(mute).connect(ctx.destination); node.port.onmessage = (e) => { const d = e.data; if (d.chunk) this.chunks.push(d.chunk); else if (d.peak !== undefined) this.onPeak?.(d.peak); else if (d.done) { const total = this.chunks.reduce((s, c) => s + c.length, 0); const out = new Float32Array(total); let o = 0; for (const c of this.chunks) { out.set(c, o); o += c.length; } this.chunks = []; this.stopResolve?.(out); this.stopResolve = null; } }; if (ctx.state !== "running") await ctx.resume(); this.ctx = ctx; this.stream = stream; this.node = node; this.info = { deviceLabel: track.label, trackSettings: settings, contextSampleRate: ctx.sampleRate, userAgent: navigator.userAgent, }; return this.info; } get sampleRate() { return this.ctx?.sampleRate ?? 0; } get isOpen() { return !!this.ctx; } start() { if (!this.node) throw new Error("Microphone is not open"); this.chunks = []; this.recording = true; this.node.port.postMessage("start"); } stop(): Promise { if (!this.node) return Promise.resolve(new Float32Array(0)); this.recording = false; return new Promise((resolve) => { this.stopResolve = resolve; this.node!.port.postMessage("stop"); }); } async close() { this.stream?.getTracks().forEach((t) => t.stop()); if (this.ctx) await this.ctx.close(); this.ctx = null; this.stream = null; this.node = null; this.recording = false; } } export async function listInputs(): Promise { const all = await navigator.mediaDevices.enumerateDevices(); return all.filter((d) => d.kind === "audioinput"); }