in Web Audio API

TSW Web Audio Primer – Part 3

In part 2 of this series, you learned how to change the pitch of a note. In this part, you will learn how to change the oscillator type. Add the following HTML logic after the slider logic from Part 2 to set up a form with radio buttons:

FROM:

<center><p><input class="slider-width200" id="slider" type="range" min="0" max="1000" value="600" onchange="changePitch(this.value)"></p></center>

TO:

<center><p><input class="slider-width200" id="slider" type="range" min="0" max="1000" value="600" onchange="changePitch(this.value)"></p></center>
<form>
<input type="radio" name="oscType" value="sine" onclick="getOscType(this.value);" checked>Sine
<input type="radio" name="oscType" value="square" onclick="getOscType(this.value);">Square
<input type="radio" name="oscType" value="triangle" onclick="getOscType(this.value);">Triangle
<input type="radio" name="oscType" value="sawtooth" onclick="getOscType(this.value);">Sawtooth
</form>

Next, we will make several changes to pitch.js. First, add a variable for the type of oscillator:

FROM:

var osc;

var volume;

TO:

var osc;

var oscType = 'sine';

var volume;

Next, we will change the turn_on function to use the new oscType variable.

FROM:

function turn_on() {

osc = tsw.oscillator (600, 'sawtooth');

tsw.connect(osc, volume, tsw.speakers);

osc.start();

};

TO:

function turn_on() {

osc = tsw.oscillator (600, oscType);

tsw.connect(osc, volume, tsw.speakers);

osc.start();

};

Finally, we will add a new function as follows:

function getOscType(value)

{

oscType = value;

osc.type(oscType)

}

This function will be called whenever a new radio button is selected, and will change the oscillator type for the current note being played.

Load index.html in your browser and you should see the following:

ex03_01

As before, click the Play button to start playing. You can change the pitch using the slider, and when you select a different radio button, the oscillator type will change for the pitch being played.

You can also go to the demo of this application and see if you can change the oscillator type.

Download the source code for all of the examples in this series from Github.

 

Write a Comment

Comment

Webmentions

  • Stuart Memo reposted this Article on twitter.com.