Spaces:
Running
Running
class SilenceDetectorProcessor extends AudioWorkletProcessor { | |
static get parameterDescriptors() { | |
return [{name: 'threshold', defaultValue: 0.01}]; | |
} | |
constructor() { | |
super(); | |
this.silenceStart = 0; | |
this.SILENCE_DELAY = 0.4; | |
} | |
process(inputs, outputs, parameters) { | |
const input = inputs[0]; | |
const threshold = parameters.threshold[0]; | |
if (input.length > 0) { | |
const inputChannelData = input[0]; | |
let sum = 0; | |
for (let i = 0; i < inputChannelData.length; i++) { | |
sum += inputChannelData[i] * inputChannelData[i]; | |
} | |
let volume = Math.sqrt(sum / inputChannelData.length); | |
if (this.silenceStart === 0) this.silenceStart = currentTime; | |
if (volume < threshold) { | |
if (currentTime - this.silenceStart > this.SILENCE_DELAY) { | |
this.port.postMessage({type: 'silence', silenceDuration: currentTime - this.silenceStart}); | |
this.silenceStart = currentTime; | |
} | |
} else { | |
this.silenceStart = currentTime; | |
this.port.postMessage({type: 'sound'}); | |
} | |
} | |
return true; | |
} | |
} | |
registerProcessor('silence-detector-processor', SilenceDetectorProcessor); | |