Building HTML5 media (video, audio) controls with JavaScript

by , Oct. 19, 2010 at 08:59 PM

Scripts: html5

With te earlier versions of HTML, it was impossible to embed and play media on a webpage along without invoking third part plugins that didn't belong to HTML itself.
Here I am talking about Flash, Silverlight, Quick times, and so on...
The great HTML5 has come with handful and nice features to enrich and innovate the web applications.
One of these is the inclusion of MediaElement. (using Audio and/or video files on a webpage as we used to with images).
You do not need Flash any more to play you media on your page unless the visitors of your page still use the old browsers or so called, the non-Advanced browser.
Then you must foresee a way to a fallback for those browsers.
Not all browsers support yet HTML5 even IE8 (InternetExplorer8) doesn't support HTML5. However, Microsoft is promising to full integrate HTML5 in IE9, wich is to come.
Those browsers which support HTML5 have their custom media controls, which look differently to each other.
Here is the sketch of different controls of browsers:Native controls

If you want to build up you own customized Media controls, it is possible because HTML5 dispose Media properties, Media events you can manipulate in the DOM to control the media object and build your own media controls.


Media properties are:
"error", "src", "currentSrc", "networkState", "preload", "buffered", "readyState", "seeking", "currentTime", "startTime", "duration", "paused", "defaultPlaybackRate", "playbackRate", "played", "seekable", "ended", "autoplay", "loop", "controls", "volume", "muted"

Media events are:
"loadstart", "progress", "suspend", "emptied","stalled", "play","pause", "loadedmetadata", "loadeddata","waiting", "playing", "canplay", "canplaythrough", "seeking","seeked", "timeupdate", "ended", "ratechange", "durationchange", "volumechange"

All these properties and events are found in the spec. of W3 from May 2010.

Now the question is how to handle all this to build a controls. Most of these properties and events are more explanatory of its own. I cannot go explaining all these events and props on here otherwise it will be worth to write up a whole book on this.
But I will try to explain some.
Note that some of the props are read-only and cannot be change in value, others can be modified.
First of all a simple example of embed a video on a webpage:

Note to wacht this movie you have to use as web-browser (Mozilla Firefox, Safari, Chrome, or IE9) because the IE7 even IE8 cannot play the MediaElement Video or Audio and many other features of HTML5.

 

With this piece of code in this HTML page you wacht this video with a native custom controls accordingly  to the browser.

  1. //Check if the event loadstart is fired
  2. var myvideo = document.getElementsByTag('video')[0];
  3. myvideo.addEventListener('loadstart', function loadStart(){
  4. alert('Start loading...');
  5. }, false);
  6.  
  7. //Check if the event loadedmetadata is fired
  8. //var myvideo = document.getElementsByTag('video')[0];
  9. myvideo.addEventListener('loadedmetadata', function loadedData(){
  10. var videoOrigWidth = myvideo.videoWidth;
  11. var videoOrigHeight = myvideo.videoHeight;
  12. alert(videoOrigWidth + ' x ' + videoOrigHeight);
  13. }, false);
  14.  
  15. //
  16. //var myvideo = document.getElementsByTag('video')[0];
  17. var loaded_div = document.getElementById('loaded');
  18. myvideo.addEventListener('progress', Progress, false);
  19. function Progress(event) {
  20. if (event.total > 0) {
  21. loaded_div.innerHTML = (Math.floor(event.loaded / event.total * 100) + "% - " + myvideo.currentSrc);
  22. setLoadProgress((event.loaded / event.total));
  23. }
  24. }

 

In the code snippet here above you see some javascript code that may control the video element in HTML. Firstly, a defining a variable to hold the video element of the DOM when this is loaded and is ready. This video element is defined as follows var myvideo = document.getElementsByTag('video')[0];

myvideo is got from DOM which keep all the video elements in this case in an array. Because we are dealing with one video element that is why we take that first element of the array.

The loadstart and loadedmetadata are events that are fired when the media is successively the media data and metadata is start loading. Metadadata are related to the information of the media, its size, its author, ...

 

  1. // define the holders of currentTime and duration of the video
  2. var myvideo = document.getElementsByTag('video')[0];
  3. var videoDuration = document.getElementById('duration');
  4. var currentTime = document.getElementById('currentTime');
  5.  
  6. // Track the timeupdate Event, this event is important because
  7. // herein you receive periodically
  8. // the current time the video or audio has played
  9. myvideo.addEventListener('timeupdate', function(e) {
  10. //split currentTime (seconds) into separate hour/minute/second strings
  11. var seconds = e.target.currentTime;
  12. var h = Math.floor(seconds / 3600);
  13. seconds = seconds % 3600;
  14. var min = Math.floor(seconds / 60);
  15. seconds = Math.floor(seconds % 60);
  16. /* pad the minute and second strings to two digits */
  17. if (seconds.toString().length < 2)
  18. seconds = "0" + seconds;
  19. if (min.toString().length < 2)
  20. min = "0" + min;
  21. videoDuration.innerHTML = e.target.duration;
  22. currentTimeDisplay.innerHTML = h + ":" + min + ":" + seconds;
  23. }, false);

 

Here the the event timeupdate is useful, because when the media start to play it will be fired automatically and periocally within several milliseconds. It return an TimeRanges Object with the propriety for currentTime wich tells how much data has been played until now, one property for the total data of the video.

To let you see how to put into practice this simple explanation of javascript how to interact with a video. Of course to markup with html and CSS is more important to give your controls a nice feel and touch.

Click on Play to play the video, Pause to pause it and << Rewind to rewind it.

 

  1. var myvideo = document.getElementsByTag("video")[0];
  2. myvideo.addEventListenenr('timeupdate', function(e){
  3. var currentT_Holder = document.getElementById('currentT');
  4. currentT_Holder.innerHTML = e.target.currentTime;
  5. }, false);
  6. <video preload width="400">
  7. <source src="HTML5/MP4/video.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
  8. <source src="HTML5/MP4/video.ogv" type='video/ogg; codecs="theora, vorbis"' />
  9. <source src="HTML5/MP4/video.webm" type='video/webm; codecs="vp8, vorbis"'/>
  10. Your browser does not support the <code>video</code> element.
  11. </video>
  12. <p>
  13. <input type="button" value="Play" onclick="myvideo.play();" />
  14. <input type="button" value="Pause" onclick="myvideo.pause();" />
  15. <input type="button" value="<< Rewind" onclick="myvideo.currentTime = 0;">
  16. <span id="currentT"></span>
  17. </p>

 

For a complete build up controls with javascript and some CSS styling visit this link :
Customized HTML5 controls with javascript

Available Comments :

Amo

Oct. 20, 2010 at 11:36 PM

HTML5 is great stuff

Your Attention! Please do not post message with spam on this blog. We try to be cool to each other and post relevant comments and relating to the appropriated topic or entry. Let's try to get a nice conversation over here.

Leave a comment

Required!
Required!

Required!
Required!

Latest News

  • Feb. 28, 2015 at 14:39
    Football's lawmakers have postponed plans in the Netherlands to trial video replays in live games.
    Read more»
  • Feb. 28, 2015 at 14:35
    Western leaders condemn the killing of Russian opposition politician Boris Nemtsov, and urge the authorities to conduct a transparent invest...
    Read more»
  • Feb. 28, 2015 at 14:24
    Iraq's national museum officially reopens in Baghdad, 12 years after it was looted in the aftermath of the invasion that toppled Saddam Huss...
    Read more»
  • Feb. 28, 2015 at 14:17
    A laptop computer is found in the search for missing 16-year-old Rebecca Watts in Bristol although police have yet to comment.
    Read more»
  • Feb. 28, 2015 at 13:58
    The jailed leader of Turkey's main Kurdish rebel group urges his followers to end a 30-year armed struggle and seek a democratic peace.
    Read more»
  • Feb. 28, 2015 at 13:46
    First-time home buyers aged under 40 in England can now register to buy new homes at a discount of up to a fifth off the normal price.
    Read more»
  • Feb. 28, 2015 at 13:33
    People in Lesotho are voting in polls aimed at resolving political tensions following an attempted coup last year.
    Read more»
  • Feb. 28, 2015 at 13:26
    Both government and opposition in Russia are coming up with theories about the killing of Putin critic Boris Nemtsov, but it could be years ...
    Read more»
  • Feb. 28, 2015 at 13:00
    A 15-year-old boy was stabbed to death when three men attacked him while he was cycling with friends, police say.
    Read more»
  • Feb. 28, 2015 at 12:45
    India bowl out United Arab Emirates for 102, the lowest total yet at the World Cup, before racing to victory in 18.5 overs.
    Read more»
  • Feb. 28, 2015 at 11:55
    President Obama is among those paying tribute to Leonard Nimoy, the Star Trek actor who has died aged 83, saying: "I loved Spock."
    Read more»
  • Feb. 28, 2015 at 11:54
    UK industry completes construction of the modules that make up the Lisa Pathfinder satellite - a remarkable probe that will test the key tec...
    Read more»
  • Feb. 28, 2015 at 11:11
    Ansar Allah, or the Houthi movement, began as a defence of the Zaidi religious tradition but experienced several major transformations in ar...
    Read more»
  • Feb. 28, 2015 at 10:19
    Fighting has died down in Ukraine's Donetsk and Luhansk regions in recent days, after a ceasefire agreed between the government and pro-Russ...
    Read more»
  • Feb. 28, 2015 at 10:17
    Energy price comparison sites should compensate customers who changed to tariffs that may not have been the cheapest deals, MPs say.
    Read more»
  • Feb. 28, 2015 at 09:25
    Indian PM Narendra Modi's government unveils a business-friendly budget aimed at attracting greater investment for the economy.
    Read more»
  • Feb. 28, 2015 at 09:07
    New Zealand survive a late collapse to beat Australia by one wicket in a thrilling climax to their World Cup Pool A game.
    Read more»
  • Feb. 28, 2015 at 09:02
    A dress "resembling" the $150,000 (£97,000) outfit worn by Lupita Nyong'o at this year's Oscars has been found, Los Angeles police say.
    Read more»
  • Feb. 28, 2015 at 07:55
    The Mexican president hails the capture of the country's most wanted drug lord - Knights Templar chief Servando 'La Tuta' Gomez.
    Read more»
  • Feb. 28, 2015 at 07:35
    Russia has become a danger to Britain and the country must be prepared to take steps to defend itself and its allies, the former head of MI6...
    Read more»

Recent Comments:

Emmanuel Ndayiragije

May. 05, 2011 at 04:30 PM

Salut Joannes,
Quand j'ai programmé ce système, je l'ai codé supportant l'englais seulement. Bientôt, je vais l'étendre pour pouvoir supporte... Read more»

Joannes

Apr. 27, 2011 at 02:16 PM

Why don't you write in french?

Administrator

Nov. 12, 2010 at 11:56 AM

The inaccuracy of the Geolocation Api of html5 may be it use the IP from your internet provider or ur pc has no GPS tools installed on it. Geolocation... Read more»

Cr.frozen

Nov. 12, 2010 at 11:33 AM

Html5 geolocation is not accurate?
How come?

Amo

Oct. 20, 2010 at 11:36 PM

HTML5 is great stuff

Archives:

Meet me on facebook: