Time for action – playing the notes
The next thing we need to do is add event handlers to play an <audio>
element when a piano key is clicked or touched. We will hook up and event handlers to all of our piano keys and play the associated note when they are fired.
Note
At the time of this writing, the state of audio on mobile devices isn't very good. Although a touch device would be perfect for a piano app, the sounds don't always play correctly because of the way mobile browsers cache audio (or not).
Let's create a method called initKeyboard()
that will be called from the application's start()
method:
function initKeyboard() { var $keys = $(".keyboard .piano-key"); if ($.isTouchSupported) { $keys.touchstart(function(e) { e.stopPropagation(); e.preventDefault(); keyDown($(this)); }) .touchend(function() { keyUp($(this)); }) } else { $keys.mousedown(function() { keyDown($(this)); ...