4.8 And What About Audio? 99
In the network state, we encounter loadstart, progress, suspend, abort, error,
emptied, and stalled, and their names indicate in which network scenarios
they appear. In the ready state are loadedmetadata, loadeddata, waiting, play-
ing, canplay, or canplaythrough, all relating directly to the availability of data
for the current or future playback position. In the playback state are play, pause,
timeupdate, ended, ratechange, and durationchange, and again their names are
as self-explanatory as is the last element we need to mention, volumechange.
When and how each event is used depends entirely on the purpose of your script.
For our video player, we needed only two, oncanplay and ontimeupdate. But if we
wanted to refine the details, we would almost certainly need many others as well.
If you want to read details on the various events, you should refer to the very
helpful Event summary in the specification. There you will find not only a
description of each event, but also indications as to when it is actually fired.
Browse to http://www.w3.org/TR/html5/video.html#mediaevents.
If you want to see media events live in action, go to Philippe Le Hégaret’s HTML5
Video, Media Events, and Media Properties test page at W3C: http://www.
w3.org/2010/05/video/mediaevents.html.
4.8 And What About Audio?
There is not much new to announce about audio in HTML5. Conveniently, video
and audio share the HTMLMediaElement interface, which means that everything
we have told you about scripting and video is also applicable to audio elements.
Understandably, the additional video attributes for width, height, audio, and
poster frame of the HTMLVideoElement interface are omitted. audio elements can
be easily created via a constructor and have a src attribute assigned to them at
the same time:
var audio = new Audio(src);
Following the pattern of our video player, let’s program an audio player for the
Big Buck Bunny soundtrack. Slider, time display, and starting or stopping work
in the same way as in the video example. A new feature is the menu for select-
ing the track: Different audio files are involved plus two buttons for jumping
ahead or backward on the track list. Additionally, we implement looping at the
end of all tracks plus random selection of the next track. You can see the result
in Figure 4.10.