Sunday, 13 July 2014

Video Player Series- Finishing our video player (Part 7/7)

In the previous posts we've worked through a lot of stuff and managed to build a video player that looks same on all browsers such that we can style it the way we want it. We also gave it custom functionality.

In this part we'll be finishing up with the video player and there's one more functionality to build: Seeking into the video when the user clicks on the progress bar.


Ah! Finally we'll finish building a video player!
Ah! Finally we'll finish building a video player!
View Demo

Seeking into the video

Let's finally talk about building a functionality to seek into the video. We'll this is really simple to do. If you recall from a previous part of this series, we built a function called init which set up all our variables and event handlers for it. If you remember we set an event listener on our backgroundBar that calls a function called seek each time it is clicked. So let's go ahead and build the function called seek.

Well, the first thing I would like to point out is that this function takes in a parameter 'e' that the browser will pass to it when it is clicked. This parameter 'e' has a property called pageX which tells us how many pixels to the left is the page from the mouse. The backgroundBar variable has a property called offsetLeft that tells us how many pixels to the left is the bar. To find out the x position of the mouse with respect to the bar we simple subtract these two values. So we end up with the following formula:
var x = e.pageX - backgroundBar.offsetLeft;
 Now that we know how far to the right from the background bar is the mouse click, it's time we determine the new time that the user sought (past tense of seek in case you didn't know) to for the video player. The way we determine when the sought time is using this formula:
newTime = x * duration / bar_width
Where x is the mouse's x position, duration is the video's total duration and bar_width is the total width of  the background bar.

One final thing we've got left is to change the progress bar's width. We do this the same way we did it in the previous part in this series.

So, let's put all of this into code:
function seek(e){
    var x = e.pageX - backgroundBar.offsetLeft;
    var t = x * player.duration / 600;
    player.currentTime = t;  
    var size = parseInt(player.currentTime*600/player.duration);
    progressBar.style.width=size+"px";
}

That's it, we're done!

We've finally completed our video player. It can play/pause and seek into video. Also, it looks completely different from the default video player's that the browsers give us.

I hope you've learned something from this series and remember, this isn't the end of your imagination, just the series, so think different and build something cool!

No comments:

Post a Comment