Loading and Playing the Audio

We are going to use the canplaythrough and progress events to load <audio> before we try to play it. Here is how we embed the audio for song1:

<audio id="theAudio" controls>
<source src="song1.mp3" type="audio/mp3">
<source src="song1.wav" type="audio/wav">
<source src="song1.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>

Similar to most of the applications we have built thus far in this book, we will create event handlers for progress and canplaythrough after the window DOM object has finished loading, and then we will call the load() method of audioElement to force the audio file to start loading:

window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
   var audioElement = document.getElementById("theAudio");
   audioElement.addEventListener('canplaythrough',audioLoaded,false);
   audioElement.addEventListener('progress',updateLoadingStatus,false);
   audioElement.load();

}

When the canplaythrough event is dispatched, canvasApp() is called. Then we start playing the audio by retrieving a reference to the audio element in the HTML page through the DOM, with a call to getElementById(). (We will create a variable named audioElement that we will use throughout the canvas application to reference the audio element in the HTML page.) We then call the play() function of audioElement:

var audioElement = document.getElementById("theAudio");
audioElement.play();

You might be wondering why we didn’t use the ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.