Search code examples
html5-audioweb-audio-api

Web audio change volume and frequency at the same time


I'm trying to have two "input range" to change the volume and frequency.

I can control them separately but cannot apply to both. I know the problem is that I try to set destination filter.connect(context.destination) and this.gainNode.connect(context.destination) at the same time. How to deal with the situation?

Here is HTML code

<p><input type="range" min="0" max="100" value="100" onchange="sample.changeVolume(this);"> Volume</p>
<p><input type="checkbox" id="c1" checked="false" onchange="sample.toggleFilter(this);">
<p><input type="range" min="0" max="1" step="0.01" value="1" onchange="sample.changeFrequency(this);"> Frequency</p>

The JavaScript code

FilterSample.prototype.play = function() {
   this.gainNode = context.createGain();
   // Create the source.
   var source = context.createBufferSource();
   source.buffer = this.buffer;
   // Create the filter.
   var filter = context.createBiquadFilter();
   filter.type = filter.LOWPASS;
   filter.frequency.value = 5000;
   // Connect source to filter, filter to destination.
   source.connect(this.gainNode);
   this.gainNode.connect(context.destination);
   source.connect(filter);
   filter.connect(context.destination);

   // Play!
   source[source.start ? 'start' : 'noteOn'](0);
   source.loop = true;
   // Save source and filterNode for later access.
   this.source = source;
   this.filter = filter;
 };

Solution

  • Try connect them in a single chain instead:

    source.connect(this.gainNode);        // source -> gain
    this.gainNode.connect(filter);        // gain -> filter
    filter.connect(context.destination);  // filter -> output
    

    (the code for sample is not shown so we cannot see if there is any errors in there).