Part 2 - Gaining Hertz

Part 2 of the Web Audio API brings in frequency manipulation of the oscillator. The basic concept of audio nodes (AudioNode) is also introduced what allows to manipulate the volume of the oscillator in the example code of this tutorial part.

First of all like in part 1 an oscillator over an audio context must be created:

var context = new AudioContext();
var oscillator = context.createOscillator();

The following code changes the frequency of the oscillator to 320.5Hz:

oscillator.frequency.value = 320.5;

For human beings audible frequencies are between 20 Hz and 20000 Hz. In the example code in the end of this part the value of the frequency can be manipulated via a slider ().
With audio nodes it is indeed possible to implement even complex routing and mixing scenarios. Audio nodes can be connected to audio sources, audio destinations or other audio nodes. The next graph (Fig. 1) shows an extension to the graph used in part 1.
Source Gain Desti- nation
Fig. 1

The here newly introduced audio node is the built-in gain node which allows to change the volume of an audio source.
This gain node can be created with the following line of code:

var volumeNode = context.createGain();

Via the audio context the createGain-method is called that gives back a gain node that can now be accessed with the volumeNode variable.
To set the gain to a certain value you need to code:

volumeNode.gain.value = 0.5;

The original volume gain is now reduced to the half.
To implement the signal flow of Fig. 1 the audio source, the audio node and the destination must be connected the correct way:

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

Now the oscillator is connected to the volumeNode and this volumeNode is connected to the audio destination. The activated oscillator sounds with a volume reduced by the factor 0.5.
The example code of the part 1 can now be extended by the discussed functionality of this part 2.

var context = new AudioContext();
var oscillator = context.createOscillator();
oscillator.type = "sine";
oscillator.start(0);
var volumeNode = context.createGain();
volumeNode.gain.value = 0.5;
oscillator.connect(volumeNode);

function startTone() {
    volumeNode.connect(context.destination);
}

function stopTone() {
    volumeNode.disconnect();
}

function changeType(value) {
    oscillator.type = value;
}

function changeFrequency(value) {
    oscillator.frequency.value = value;
}

function changeVolume(value) {
    volumeNode.gain.value = value;
}

In comparison to the code of part 1 there is now a method changeFrequency that changes the frequency of the oscillator. A connection between the oscillator and the new discussed volumeNode is set. Also the changeVolume-method is newly inserted which changes the gain of the oscillator. Therefore the methods startTone and changeTone are changed to connect and disconnect the volumeNode and the destination.




Frequency: 440.0 Hz
Volume: 0.5