murmuraba
Version:
Real-time audio noise reduction with advanced chunked processing for web applications
65 lines (64 loc) • 1.8 kB
JavaScript
/**
* Energy-based Voice Activity Detection
*/
export class EnergyVAD {
constructor() {
this.noiseFloor = 0;
this.adaptiveThreshold = 0.01;
this.smoothingFactor = 0.95;
}
/**
* Calculate RMS energy of audio frame
*/
calculateEnergy(frame) {
let sum = 0;
for (let i = 0; i < frame.length; i++) {
sum += frame[i] * frame[i];
}
return Math.sqrt(sum / frame.length);
}
/**
* Update noise floor estimate
*/
updateNoiseFloor(energy, isSpeech) {
if (!isSpeech) {
// Update noise floor with exponential averaging
this.noiseFloor = this.smoothingFactor * this.noiseFloor +
(1 - this.smoothingFactor) * energy;
// Update adaptive threshold
this.adaptiveThreshold = Math.max(0.01, this.noiseFloor * 3);
}
}
/**
* Detect voice activity based on energy
*/
detect(frame) {
const energy = this.calculateEnergy(frame);
// Simple thresholding with adaptive component
const threshold = Math.max(this.adaptiveThreshold, 0.01);
const vadScore = Math.min(1, energy / threshold);
// Update noise floor if likely non-speech
if (vadScore < 0.5) {
this.updateNoiseFloor(energy, false);
}
return vadScore;
}
/**
* Calculate energy metrics for a frame
*/
getMetrics(frame) {
const energy = this.calculateEnergy(frame);
return {
energy,
noiseFloor: this.noiseFloor,
threshold: this.adaptiveThreshold
};
}
/**
* Reset the detector state
*/
reset() {
this.noiseFloor = 0;
this.adaptiveThreshold = 0.01;
}
}