web-audio Getting started with web-audio Synthesising audio

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any web-audio Question?