To create a filter, instantiate an instance of BiquadFilterNode
. In the
signal chain, hook up an OscillatorNode
to it's GainNode
, it's GainNode
to the filter, then the filter to the dac. It is important you pick a
frequency-rich waveform like "sawtooth"
or "square"
, because it will be
difficult or impossible to hear the filter's effects on a frequency-poor
waveform like "triangle"
or "sine"
.
const audioCtx = new AudioContext();
const oscillator = audioCtx.createOscillator();
oscillator.frequency.value = 220;
oscillator.type = "sawtooth";
const oscillatorGain = audioCtx.createGain();
oscillatorGain.gain.value = 0.1;
const filter = audioCtx.createBiquadFilter();
oscillator.connect(oscillatorGain);
oscillatorGain.connect(filter);
filter.connect(audioCtx.destination);
oscillator.start();
Filters have a number of properties you may customize. The .type
property
may be set to basic filter types like "lowpass"
, "highpass"
, and
"bandpass"
, as well as more advanced types like "peaking"
and "notch"
.
The .frequency
and .detune
properties may be used to set the cutoff
frequency. In conjunction with the .Q
property, you may fine-tune your
filter.
filter.type = "lowpass";
filter.frequency.value = 660;
filter.Q.value = 20;
You may also hook up an LFO to the filter properties. You may change all of
the properties that are AudioParam
s: .frequency
, .detune
, and .Q
.
const modulator = audioCtx.createOscillator();
const modulatorGain = audioCtx.createGain();
// set modulator parameters
modulator.connect(modulatorGain);
modulatorGain.connect(filter.frequency);
modulator.start();
Download the files used in the above examples by right-clicking the links, and then selecting "Save Link As...".
BiquadFilterNode
In this item, you only applied a filter to a basic waveform. Try applying different filters to:
Create a button that performs a "filter sweep", i.e. a steady decrease of the filter cutoff frequency over time. (This will sound great over a sound file of a drum break!) You may have to look ahead to the next lesson on envelopes.