Search code examples
javascriptaudiotypeerrorweb-audio-api

Why does JS throw a Type Error when I try to connect audio to a Biquad Filter?


I’ve been dabbling in the WebAudio API, and for some reason I cannot get the Biquad Filter to work. My oscillators, envelopes, and custom effects all work fine, but the filter has been giving me trouble.

I have a master gain control vca which I want to send through my filter out to context.destination. vca is defined simply as such:

var vca = context.createGain();
vca.gain.value = 0.3

I’ve built my filter like this:

function lowpass() {
  var filter = context.createBiquadFilter();
  filter.type = 'lowpass';
  filter.frequency.value = 1000
}
var filt = new lowpass

When I attempt to run the following, CodePen throws a Type Error:

vca.connect(filt);
filt.connect(context.destination)

Why is this happening? Is it something wrong with the filter settings, my method of connecting the VCA? The way I’ve constructed the filter? Thanks.


Solution

  • It's the way you create a new filter. lowpass() is a regular function but the new keyword treats it like a constructor.

    You can fix your code by calling it as a regular function and returning the filter from it.

    function lowpass() {
      var filter = context.createBiquadFilter();
      filter.type = 'lowpass';
      filter.frequency.value = 1000
      return filter;
    }
    var filt = lowpass()
    

    If want to go one step further you can pass the context into the function instead of relying on context to be defined in the outer scope to make it a bit cleaner.

    function lowpass(context) {
      var filter = context.createBiquadFilter();
      filter.type = 'lowpass';
      filter.frequency.value = 1000
      return filter;
    }
    var filt = lowpass(context)