Generating a tone using pure javascript with Chromium WebAudio API

Alex Churchill picture Alex Churchill · Jul 29, 2011 · Viewed 8.3k times · Source

How can I generate a tone (pure sine wave, for instance) using only javascript and Chromium's WebAudio API?

I would like to accomplish something like the Firefox equivalent.

The Chromium WebAudio demos here appear to all use prerecorded <audio> elements.

Thanks!

Answer

Stuart Memo picture Stuart Memo · Jun 20, 2012

The Web Audio API has what's known as the Oscillator Interface to generate the tones you're talking about. They're pretty straight forward to get going...

var context = new webkitAudioContext(),
    //Call function on context
    oscillator = context.createOscillator(); // Oscillator defaults to sine wave

oscillator.connect(context.destination);
oscillator.start();

You can change the type of wave by doing:

oscillator.type = 1; // Change to square wave.

or alternatively:

oscillator.type = oscillator.SQUARE;

I've written an article about this very topic in more detail, so that might be of some use to you!