Time for action – adding a sustain control

Let's go ahead and add a sustain control to the application. We will use a checkbox input control to turn sustain on and off. In our HTML file, we will add a new <div> element with a class of controls under the keyboard to hold our controls:

<div id="main">
    <!-- keyboard not shown... -->
    <div class="controls">
        <label for="sustain">Sustain: </label>
        <input type="checkbox" id="sustain" checked /><br />
    </div>
</div>

We define a label and a checkbox with an id attribute of sustain. We also set it checked by default.

Now let's implement the code for the checkbox in our PianoApp application object. First, we need to add a variable named sustain and set it to true:

function PianoApp()
{
    var version = "6.3",
    // Code not shown...
    sustain = true;

Next, we hook up a change event handler to get notified when the checkbox changes. We will do this in the application's start() method:

$("#sustain").change(function() { sustain = $(this).is(":checked"); });

When the checkbox changes, we figure out if it is checked using the jQuery is() filter method passing it the :checked filter. If it is checked, the sustain variable gets set to true.

Now we need to make some changes to the keyUp() method. All the method does now is to remove the down class from the piano-key element. We need to add code to check the sustain variable and stop the sound from playing if this variable is set to true:

function keyUp($key)
{
    $key.removeClass("down");
    if (!sustain)
    {
        var noteName = $key.data("note");
        var audio = audioManager.getAudio(escape(noteName));
        audio.pause();
    }
}

After removing the down class, we check the sustain variable. If sustain is not set, we get the note name from the piano-key element's data-note custom attribute and use that to get the <audio> element from the audioManager object. Then we call the pause() method to stop playing the sound.

What just happened?

We added a checkbox to allow the user to turn the sustain control on and off. When sustain is off and the user releases a piano key, we call the Audio API's pause() method to stop playback of the note.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.31.209