MicProtocol / apps /web /src /lib /audio /diagnostics.ts
Benaah's picture
Upload folder using huggingface_hub
fb12607 verified
Raw History Blame Contribute Delete
3.9 kB
export interface DiagnosticsResult {
rt60: number | null;
emiNoiseDetected: boolean;
noiseFloorDb: number | null;
}
export class AudioDiagnostics {
private stream: MediaStream | null = null;
private audioContext: AudioContext | null = null;
private analyser: AnalyserNode | null = null;
async requestPermissions(): Promise<boolean> {
try {
this.stream = await navigator.mediaDevices.getUserMedia({
audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false }
});
return true;
} catch (err) {
console.error('Microphone permission denied', err);
return false;
}
}
async runFullDiagnostic(): Promise<DiagnosticsResult> {
if (!this.stream) throw new Error('Microphone stream not active');
this.audioContext = new AudioContext({ sampleRate: 48000 });
const source = this.audioContext.createMediaStreamSource(this.stream);
this.analyser = this.audioContext.createAnalyser();
// High resolution for 50/60Hz detection
this.analyser.fftSize = 4096;
source.connect(this.analyser);
const emiNoiseDetected = await this.detectEmiHum();
const noiseFloorDb = await this.measureNoiseFloor();
const rt60 = await this.estimateRt60(); // Requires user clap later
return { rt60, emiNoiseDetected, noiseFloorDb };
}
private async detectEmiHum(): Promise<boolean> {
return new Promise((resolve) => {
if (!this.analyser || !this.audioContext) return resolve(false);
const bufferLength = this.analyser.frequencyBinCount;
const dataArray = new Float32Array(bufferLength);
// Sample for 2 seconds to detect persistent hum
setTimeout(() => {
this.analyser!.getFloatFrequencyData(dataArray);
const sampleRate = this.audioContext!.sampleRate;
// Check 50Hz (Europe/Africa) and 60Hz (US)
const bin50Hz = Math.floor(50 * this.analyser!.fftSize / sampleRate);
const bin60Hz = Math.floor(60 * this.analyser!.fftSize / sampleRate);
// If the power at 50/60Hz is significantly higher than surrounding bins (+15dB)
const targetPower = Math.max(dataArray[bin50Hz], dataArray[bin60Hz]);
const baselinePower = (dataArray[bin50Hz - 2] + dataArray[bin50Hz + 2]) / 2;
if (targetPower - baselinePower > 15) {
resolve(true); // EMI Coil Whine detected
} else {
resolve(false);
}
}, 2000);
});
}
private async measureNoiseFloor(): Promise<number> {
return new Promise((resolve) => {
if (!this.analyser) return resolve(-100);
setTimeout(() => {
const dataArray = new Float32Array(this.analyser!.fftSize);
this.analyser!.getFloatTimeDomainData(dataArray);
let sumSquares = 0;
for (let i = 0; i < dataArray.length; i++) {
sumSquares += dataArray[i] * dataArray[i];
}
const rms = Math.sqrt(sumSquares / dataArray.length);
const dbLfs = 20 * Math.log10(rms || 0.0001);
resolve(dbLfs);
}, 1000);
});
}
private async estimateRt60(): Promise<number | null> {
// In a full implementation, we would instruct the user to clap,
// record the IR (Impulse Response), calculate the Schroeder integration,
// and find the T60 decay curve.
// Mocking for the blueprint architecture:
return 0.45; // seconds
}
close() {
this.stream?.getTracks().forEach(t => t.stop());
this.audioContext?.close();
}
}