Search code examples
javascriptweb-audio-api

Web Audio API - calculate cumulative gain of filters


MediaStreamAudioSourceNode is configured with several chained and overlapping BiquadFilterNodes. Each filter has different frequencies, gains and qualities. How can one calculate total gain of these biquad filters?

This gain is necessary to prevent clipping. Knowing the gain, I'll be able to add a GainNode to lower the volume to prevent clipping.


Solution

  • For each BiquadFilterNode, use getFrequencyReponse to get the frequency response of the filter, using the same frequencyHz array. Each of these will have a magResponse array. Multiply these together, element-wise to get the combined response.

    Element 0 is the DC gain. You could use this (the reciprocal) for the gain value of the GainNode. But this might allow other frequencies to get clipped, so you might want to find the largest value in the combined response and use that. However, this might cause the volume to be very low, depending on the filters being used.