See the code below. How I understand things:
beat
is a square wave oscillating between -1 and 1.
Connecting beat
to multiplier.gain
adds the square wave of beat
to the default gain of 1. The result is a gain that oscillates between 0 and 2.
As tone
is connected to multiplier
, I expect to hear a tone of 440Hz for two seconds, then a pause for two seconds, then the tone again, and so on.
However, where I expect the gain to be 0, I still hear a tone, only muted. What am I doing wrong?
I tested with Chrome 74 and Firefox 66, both on Windows 10.
Code:
<!doctype html>
<meta charset=utf-8>
<script>
var context = new window.AudioContext();
var tone = context.createOscillator();
var beat = context.createOscillator();
beat.frequency.value = 0.25;
beat.type = "square";
var multiplier = context.createGain();
tone.connect(multiplier);
beat.connect(multiplier.gain);
multiplier.connect(context.destination);
tone.start();
beat.start();
</script>
<button onclick="context.resume()">Play</button>
The problem is that the 'square' type doesn't really oscillate between -1 and 1. The range is more or less from -0.848 to 0.848. Setting the GainNode's gain AudioParam to this value should work.
multiplier.gain.value = 0.848;
To see the actual output of an oscillator you could for example use Canopy. It can run Web Audio code and then visualizes the results.
If you do for example execute the following snippet, it will show you the corresponding waveform.
var osc = new OscillatorNode(context);
osc.type = "square";
osc.connect(context.destination);
osc.start();
I hope this helps.