Search code examples
javascriptweb-audio-api

How do I control the gain of the output?


I have created an Audio context with an oscillator but I can't control the gain of the output, even with gainNode.gain.value :

var AudioContext = window.AudioContext || window.webkitAudioContext;  
var audioctx = new AudioContext();
var gainNode = audioctx.createGain();

var oscillator = audioctx.createOscillator(); 
var oscillator2 = audioctx.createOscillator();

oscillator.connect(audioctx.destination);
oscillator.start(0);
gainNode.connect(audioctx.destination);
gainNode.gain.value = 0;

Solution

  • You need to connect the oscillator to the gain node, not the destination:

    oscillator.connect(gainNode);
    oscillator.start(0);
    gainNode.connect(audioctx.destination);
    gainNode.gain.value = 0;