Stuart Memo

Making sine, square, sawtooth and triangle waves

June 17th, 2012

If you’re wanting to use the Web Audio API to make a synthesizer, there are four main types of sound wave you’ll need to be familiar with first. These are sine, square, triangle and sawtooth. A sine wave is named after the fact that the sine function can be used to create the shape of the wave; the others are simply named after how they look:

You might be worried that we’re going to have to implement the functions that create these waves ourselves. Don’t be! We’ve got the Web Audio API’s Oscillator Interface on our side!

Oscillator Interface

Creating sound waves in any of the aforementioned four shapes is really easy. Firstly, we create an oscillator like so:

    var context = new webkitAudioContext(),
        oscillator = context.createOscillator();

The oscillator creates an audio source based on a repeating wave. It just so happens that the default wave that the oscillator uses is a sine wave, meaning that all we have to do in order to hear it is to connect it to an output and turn it on:

    oscillator.connect(context.destination); // Connect to speakers
    oscillator.start(0); // Start generating sound immediately

Lovely. If you’re following along at home then you should be hearing the nice round tone of a sine wave. So, what about the other types of waves? Well, all we have to do is tell the oscillator what type of wave we want to use by specifying a number from 0-3.

    oscillator.type = 1; // Tell the oscillator to use a square wave

Each wave has its own number.

Frequency

“Mister! I’ve got that working but I want to make a different note! This one’s boring!” Ok, ok, calm down. If we want to change the pitch of the note then we can change the frequency of the wave like so:

    oscillator.frequency.value = 900; // in hertz

Beautiful! If you can’t wait to try this out I’ve stuck it in a fiddle for instant satisfaction.