web-audio Getting started with web-audio Synthesising audio


Example

In this example we show how to generate a simple sine wave, and output it on the user's speakers/headphones.

let audioContext = new (window.AudioContext || window.webkitAudioContext)();

let sourceNode = audioContext.createOscillator();
sourceNode.type = 'sine';
sourceNode.frequency.value = 261.6;
sourceNode.detune.value = 0;

//Connect the source to the speakers
sourceNode.connect(audioContext.destination);

//Make the sound audible for 100 ms
sourceNode.start();
window.setTimeout(function() { sourceNode.stop(); }, 100);

The start and stop methods of the sourceNode variable above each have an optional parameter when that specifies how many seconds to wait before starting or stopping.

So, an alternative way to stopping the sound would be:

sourceNode.start();
sourceNode.stop(0.1);

The type parameter of an oscillator node can be set to any of the following values:

  • sine (default)
  • square
  • sawtooth
  • traingle
  • a custom wave

Custom waves are PeriodicWaves and can be created using the AudioContext.createPeriodicWave method.