Electronic Music Tools with JavaScript: Week 2

This is the second post in a series following my progress on the course Learn to Code Electronic Music Tools with JavaScript on FutureLearn. Here is the first post.

Week 2 - Make a User Interface for the Synthesizer

Week 2 focuses on creating instruments with more sophisticated user interfaces using the Nexus UI library.

A More Recognisable Synth

Here is an example of a basic synthesizer I created using the library. I used the nexus keyboard widget to get a more traditional interface. When a key is pressed the nx.mtof function is called to convert the MIDI value into the corresponding frequency and the oscillators frequency is set to match. When keys are pressed and released the callback data includes an ‘on’ property which signifies if the key is being pressed or released. When the key is released the volume of the oscillator is set to zero, this way notes can be sustained for any desired duration and then immediately released. This is a contrast to the theremin I made in week 1 which sustained constantly.

<canvas id="keyboard" nx="keyboard" width="500"></canvas>
<canvas id="volumeControl" nx="dial" label="volume"></canvas>
var keyboard, volumeControl;
var audio_context = window.AudioContext || window.webkitAudioContext;

var context = new audio_context();

var osc = context.createOscillator();

var volume = context.createGain();
volume.gain.value = 1.00;

var on = false;
var play = false;
nx.onload = function() {
    keyboard.on("*", function(data) {
        if (!on) {
            on = true;
        if (data.on === 0) {
            volume.gain.value = 0.00;
            play = false;
        else {
            volume.gain.value = volumeControl.val.value;
            play = true;
        osc.frequency.setValueAtTime(nx.mtof(data.note), context.currentTime);
    volumeControl.set({value: 1.00});
    volumeControl.on("*", function(data) {
        if (play) {
            volume.gain.value = data.value;

Thoughts on Week 2

Nexus UI is great for quickly building a user interface for music tools. The example I’ve shown here is quite traditional but the library also provides interfaces for more adventurous interfaces such as the tilt sensor widget for control via mobile movements as shown in the course.

What’s Next?

Week 3 will be exploring creating rhythmic music by making a drum machine with sampled sounds!

JavaScript Web Web Audio