Tuesday, May 29, 2012

Adding Fast-Forward and Rewind Buttons with HTML5

Yes, it’s back to adding buttons I’m afraid. But you’re a dab hand at adding them by now, so I won’t need to tell you what to do until you get to the JavaScript stage.

Let’s define the buttons and throw in the function names for the onclick events because you now know what’s what:
<button id=”rewind” title=”reverse” onclick=”changePlaybackSp
eed(‘-’);” >&laquo;</button>
<button id=”ffwd” title=”fast forward” onclick=”changePlaybackSp
eed(‘+’);” >&raquo;</button>
You’ll use the HTML entities &laquo; and &raquo; to mimic the typical symbols you find on such buttons: « and » respectively.
Notice that the name of the function you’ll define is changePlaybackSpeed(). The attribute that you’ll change to make this work is the playbackRate attribute that you encountered in Table 5.1.

There is a caveat though: Currently, only the WebKit-based browsers, Safari and Chrome, support the playbackRate attribute. Therefore, the only way you can sort of mimic the intended functionality on other browsers is to alter the video’s currentTime attribute, moving it either forward or backwards:
function changePlaybackSpeed(direction) {
     if (video.playbackRate != undefined) {
          if (direction == “-”) video.playbackRate -= 1;
          else video.playbackRate += 1;
     }
     else {
          if (direction == “-”) video.currentTime -= 1;
          else video.currentTime += 1;
     }
}
If video.playbackRate is defined, you check the direction parameter passed in—again “-” for back and “+” for forward—and decrease or increase playbackRate accordingly. If the playbackRate is 0, the video is effectively paused and playback stops. Otherwise, you move the video’s currentTime backwards or forward by 1.
TIP: Although Safari and Chrome support the playbackRate attribute, they work in different ways. Both support the incrementing of the parameter to fast forward, but Chrome doesn’t support rewinding. Safari on the other hand actually starts to play the video backwards, right to the start.
Your simple but slightly more awesome than it was at the start of the chapter media player now has a full set of rather grey but functional buttons and a working progress bar (Figure 5.7).

With a bit of jiggery pokery with CSS, you can style the player to your taste and achieve what you see in Figure 5.8 or perhaps something better.

Just when you thought you were finished with this simple media player, you’ll make one final addition to increase its awesomeness—progress bar seek functionality.
NOTE: The code for this styled player and for the unstyled player is available on the website at www.html5multimedia.com.