HTML and CSS Reference
In-Depth Information
Similar to most of the applications we have built thus far in this topic, we will create
event handlers for
progress
and
canplaythrough
once the
window
DOM object has fin-
ished loading, and then 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('progress',updateLoadingStatus,false);
audioElement.addEventListener('canplaythrough',audioLoaded,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 may be wondering why we didn't use the
preload
attribute of
HTMLAudioElement
instead of forcing it to load by listening for the
canplaythrough
event. There are two
reasons for this, and both apply to the
video
element as well. First, you want to preload
so that you are sure the assets you need are available to your program at runtime.
Second, preloading ensures that the user will see something useful or interesting while
everything is loading. By using the standard
preload
attribute, you (in theory) force
your audio assets to load before the page loads. Because canvas apps are interactive
and may require many more assets than those loaded when the page loads, we avoid
the
preload
attribute and load the assets within the application.
Displaying Attributes on the Canvas
Now we are going to display the attribute values of an
audio
element playing on an
HTML page. In this example (
CH7EX3.html
), we are also going to display the
audio
element in the HTML page so you can see the relationship between what is shown on
the canvas and the state of the
<audio>
tag in the page.
In the
drawScreen()
function we will add the following code to display the attributes
of the
audioElement
variable:
context.fillStyle = "#000000";
context.fillText ("Duration:" + audioElement.duration, 20 ,20);
context.fillText ("Current time:" + audioElement.currentTime, 20 ,40);
context.fillText ("Loop: " + audioElement.loop, 20 ,60);
context.fillText ("Autoplay: " +audioElement.autoplay, 20 ,80);
context.fillText ("Muted: " + audioElement.muted, 20 ,100);
context.fillText ("Controls: " + audioElement.controls, 20 ,120);
context.fillText ("Volume: " + audioElement.volume, 20 ,140);