HTML5 Guidelines for Web Developers

(coco) #1
4.8 And What About Audio? 101

Let’s start with the audio element:


<audio src="music/bbb_01_intro.ogg"
oncanplay="canPlay()"
ontimeupdate="updateProgress()"
onended="continueOrStop()">



On loading the page, we set the src attribute to the first track and define three
callbacks. You have already encountered the updateProgress()function, which
moves the slider along and updates the time display (see Listing 4.1). The two
new callbacks are canPlay(), which is called when a track is ready to play, and
continueOrStop(), which decides what to do next at the end of a track. The on-
canplay callback canPlay() is rather short and looks like this:


canPlay = function() {
curPos.max = audio.duration;
if (pbStatus.keepPlaying == true) {
_play();
}
};


Obviously, curPos.max adapts the slider’s max attribute, just as in the video player,
but what is the subsequent if block all about? The answer is simple: We try to
take the current playback status into account and only keep playing if the player
was already in play mode.


So the status of the Play button determines if the audio player starts playing after
switching to another track. If it is playing, it should keep playing after every track
change, but if it is paused, it should only switch tracks and stay paused. This may
sound complicated, but the implementation in the play button’s callback is easy;
we just add the following code:


pbStatus.keepPlaying =
(pbStatus.keepPlaying == true)? false : true;


This alternates the status variable pbStatus.keepPlaying between true and false
with every click, and the correct decision is reached in canPlay().

Free download pdf