javascriptaudioweb-audio-apisynthesizer

How to create beat by multiplying square wave with tone?


See the code below. How I understand things:

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>

Solution

  • 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.