in Web Audio API

TSW Web Audio Primer – Part 4

Now that you have had some fun with changing a note via a slider, let’s move on to playing a note using a keyboard. Stuart Memo has created a virtual keyboard app called Qwerty Hancock for his site demo, source code at Github. We will modify our app to use this keyboard app to play a note in addition to the Play button.

First, we will make some changes to index.html. We will need to add a <div> element for the keyboard, add a <script> tag for the Qwerty Hancock logic, and move the <script> tag for pitch.js to be below the <script> tag for Qwerty Hancock. In the <head> element, make the following change:

FROM:

<script src="tsw.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="pitch.js"></script>
<!-- Custom styles for this template -->

TO:

<script src="tsw.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Custom styles for this template -->

After the <form> closing tag, add the following:

FROM:

</form>
</div>

</div><!-- /.container -->

TO:

</form>
</div>
<div id="keyboard"></div>
<script src="qwerty-hancock.js"></script>
<script src="pitch.js"></script>

</div><!-- /.container -->

In pitch.js, we will add the following new logic at the end of the file:

var context = new AudioContext();

var settings = {

id: 'keyboard',

width: 600,

height: 150,

startNote: 'A2',

whiteNotesColour: '#fff',

blackNotesColour: '#000',

borderColour: '#000',

activeColour: 'yellow',

octaves: 2

};

var keyboard = new QwertyHancock(settings);

keyboard.keyDown = function (note, frequency) {

turn_on();

changePitch(frequency)

};

keyboard.keyUp = function (note, frequency) {

turn_off();

};

This is logic taken from the Qwerty Hancock demo page. The functions turn_on and turn_off from the earlier examples are being used to start and stop the note and the changePitch function is used to get the frequency for the note corresponding to the key pressed on the keyboard.

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

ex04_01

When you click on any of the keys in the virtual keyboard, you should hear a note. You can still use the radio buttons above to change the oscillator type. You can also use letter keys on the physical keyboard to play notes (“A” through “,” for white keys, “W” through “]” for black keys). If you press more than one key at a time, you will hear a note for each key, but then the notes will not stop when the keys are released. You can refresh the web app to stop the notes.

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