Controlling Web Audio API Volume

by Vince Aggrippino

HTML

<html>
<h1>Using the Gain Node</h1>
    <p><a href="http://stuartmemo.com/controlling-web-audio-api-volume-using-the-html5-slider-element/" target="_blank">Related blogpost</a></p>
    <p>Volume</p>
<input id="volume" type="range" min="0" max="1" step="0.1" value="0.5"/>
</html>

JavaScript

var context = new window.AudioContext(),
    sineWave = context.createOscillator(),
    gainNode = context.createGain();

sineWave.frequency.value = 900;
sineWave.connect(gainNode);
gainNode.connect(context.destination);
sineWave.noteOn(0);

document.getElementById('volume').addEventListener('change', function() {
    gainNode.gain.value = this.value;
});