HTML and CSS Reference
In-Depth Information
Loading and Playing the Audio
Wearegoingtousethe
canplaythrough
and
progress
eventstoload
<audio>
beforewetry
to play it. Here is how we embed the audio for
song1
:
<audio
<audio id=
"theAudio"
controls>
<source
<source src=
"song1.mp3"
type=
"audio/mp3"
>
<source
<source src=
"song1.wav"
type=
"audio/wav"
>
<source
<source src=
"song1.ogg"
type=
"audio/ogg"
>
Your browser does not support the audio element.
</audio>
</audio>
Similar to most of the applications we have built thus far in this topic, we will create event
handlers for
progress
and
canplaythrough
after the
window
DOM object has finished load-
ing, and then we will call the
load()
method of
audioElement
to force the audio file to start
loading:
window
.
addEventListener
(
'load'
,
eventWindowLoaded
,
false
false
);
function
function
eventWindowLoaded
() {
var
var
audioElement
=
document
.
getElementById
(
"theAudio"
);
audioElement
.
addEventListener
(
'canplaythrough'
,
audioLoaded
,
false
false
);
audioElement
.
addEventListener
(
'progress'
,
updateLoadingStatus
,
false
false
);
audioElement
.
load
();
}
Whenthe
canplaythrough
eventisdispatched,
canvasApp()
iscalled.Thenwestartplaying
theaudiobyretrievingareferencetothe
audio
elementintheHTMLpagethroughtheDOM,
with a call to
getElementById()
. (We will create a variable named
audioElement
that we
willusethroughoutthecanvasapplicationtoreferencethe
audio
elementintheHTMLpage.)
We then call the
play()
function of
audioElement
:
var
var
audioElement
=
document
.
getElementById
(
"theAudio"
);
audioElement
.
play
();
You might be wondering why we didn't use the
preload
attribute of
HTMLAudioElement
in-
stead 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 en-
sures 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 can require many more assets than