Building HTML5 media (video, audio) controls with JavaScript
by Administrator, Oct. 19, 2010 at 08:59 PM
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:
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.
//Check if the event loadstart is fired var myvideo = document.getElementsByTag('video')[0]; myvideo.addEventListener('loadstart', function loadStart(){ alert('Start loading...'); }, false); //Check if the event loadedmetadata is fired //var myvideo = document.getElementsByTag('video')[0]; myvideo.addEventListener('loadedmetadata', function loadedData(){ var videoOrigWidth = myvideo.videoWidth; var videoOrigHeight = myvideo.videoHeight; alert(videoOrigWidth + ' x ' + videoOrigHeight); }, false); // //var myvideo = document.getElementsByTag('video')[0]; var loaded_div = document.getElementById('loaded'); myvideo.addEventListener('progress', Progress, false); function Progress(event) { if (event.total > 0) { loaded_div.innerHTML = (Math.floor(event.loaded / event.total * 100) + "% - " + myvideo.currentSrc); setLoadProgress((event.loaded / event.total)); } }
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, ...
// define the holders of currentTime and duration of the video var myvideo = document.getElementsByTag('video')[0]; var videoDuration = document.getElementById('duration'); var currentTime = document.getElementById('currentTime'); // Track the timeupdate Event, this event is important because // herein you receive periodically // the current time the video or audio has played myvideo.addEventListener('timeupdate', function(e) { //split currentTime (seconds) into separate hour/minute/second strings var seconds = e.target.currentTime; var h = Math.floor(seconds / 3600); seconds = seconds % 3600; var min = Math.floor(seconds / 60); seconds = Math.floor(seconds % 60); /* pad the minute and second strings to two digits */ if (seconds.toString().length < 2) seconds = "0" + seconds; if (min.toString().length < 2) min = "0" + min; videoDuration.innerHTML = e.target.duration; currentTimeDisplay.innerHTML = h + ":" + min + ":" + seconds; }, 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.
<script> var myvideo = document.getElementsByTag("video")[0]; myvideo.addEventListenenr('timeupdate', function(e){ var currentT_Holder = document.getElementById('currentT'); currentT_Holder.innerHTML = e.target.currentTime; }, false); </script> <video preload width="400"> <source src="HTML5/MP4/video.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' /> <source src="HTML5/MP4/video.ogv" type='video/ogg; codecs="theora, vorbis"' /> <source src="HTML5/MP4/video.webm" type='video/webm; codecs="vp8, vorbis"'/> </video> <p> <input type="button" value="Play" onclick="myvideo.play();" /> <input type="button" value="Pause" onclick="myvideo.pause();" /> <input type="button" value="<< Rewind" onclick="myvideo.currentTime = 0;"> </p>
For a complete build up controls with javascript and some CSS styling visit this link :
Customized HTML5 controls with javascript
Post Comment|
Permant linksAvailable Comments :
Amo
Oct. 20, 2010 at 11:36 PM
HTML5 is great stuff
Cheap online prescription glasses
Jun. 27, 2012 at 03:47 PM
I was suggested this blog by my cousin. I am not sure whether this post is
written by him as nobody else know such detailed about my difficulty.
You are wonderful! Thanks!
Emmanuel Ndayiragije
Jun. 29, 2012 at 05:27 PM
Reaction to "Cheap online prescription glasses".
Thanks for your appreciation to my blog.
Of course this blog is about to publish my own experiences I have with web programming and some of the nice features added to the Web.
Mostly features that are not yet popular, but yet outstanding and at same time exciting.
As you see this is blog entry treats the greatness of HTML 5 Video Element.
Best regards,
Owner of Emmanuelndayiragije.com
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.
Entry Categories:
Latest News
- May. 24, 2013 at 10:12
Heathrow runways are closed to enable a plane to make an emergency landing.
Read more» - May. 24, 2013 at 10:08
Shares in Japan have closed 0.89% higher, one day after Thursday's global sell-off in shares.
Read more» - May. 24, 2013 at 10:01
Stage 19 of the Giro d'Italia, to be held on Friday, is cancelled because of heavy snow.
Read more» - May. 24, 2013 at 09:55
London Market Report
Read more» - May. 24, 2013 at 09:28
A strong earthquake strikes off the Kamchatka peninsula in Russia's far east, but an initial tsunami warning issued by the authorities is li...
Read more» - May. 24, 2013 at 09:06
Preventing the killing of a British soldier on a London street would have been "incredibly hard", MI6's former head of counter-terrorism say...
Read more» - May. 24, 2013 at 08:56
Three soldiers are killed in an ambush by suspected militants in the Pulwama district of Indian-administered Kashmir, officials say.
Read more» - May. 24, 2013 at 08:51
Officers in Londonderry admit the Radio 1 event is their biggest police operation this year and they will "curb any anti-social behaviour".
Read more» - May. 24, 2013 at 08:44
Some drugs taken to protect the heart may increase the risk of developing Type-2 diabetes, according to researchers in Canada.
Read more» - May. 24, 2013 at 08:26
Iraq appears to be slipping back into mire of sectarian killings
Read more» - May. 24, 2013 at 08:19
Nightly riots highlight Sweden's inequalities
Read more» - May. 24, 2013 at 07:53
President Obama defends the use of drones as a "just war" of self-defence against deadly militants, and a campaign that has made America saf...
Read more» - May. 24, 2013 at 07:01
Watch the latest news summary from BBC World News. International news updated 24 hours a day.
Read more» - May. 24, 2013 at 06:55
Three people have been rescued after part of a road bridge collapsed into the Skagit River in the US state of Washington, officials say.
Read more» - May. 24, 2013 at 06:44
An independent report highlights faults in the way Rochdale Council dealt with child sex grooming.
Read more» - May. 24, 2013 at 06:33
The remains of King Richard III, discovered under a city car park, were buried in a "hastily dug, untidy grave", researchers reveal.
Read more» - May. 24, 2013 at 06:08
The Church of Scotland's General Assembly approves a call to crown monarchs in both England and Scotland, should Scotland becomes independen...
Read more» - May. 24, 2013 at 06:06
Fresh tussle over legacy of Guatemala's civil war
Read more» - May. 24, 2013 at 05:53
Japanese Prime Minister Shinzo Abe heads to Burma for economic talks - in the first visit by a Japanese PM since 1977.
Read more» - May. 24, 2013 at 03:57
US forecasters predict an "active or extremely active" Atlantic hurricane season of seven to 11 hurricanes, up from the average of six.
Read more»
Recent Comments:
May. 07, 2013 at 10:57 AM
Pleasing to find soemone who can think like that
May. 07, 2013 at 10:51 AM
Thinking like that is really amaizng
Oct. 27, 2012 at 03:57 PM
That framework (Kazinduzi) is right good, & simple to use, i download it and set it on my ubuntu box, it just works fine. good work, man.
Oct. 27, 2012 at 03:56 PM
Great framework, it works fine on my server.
Jun. 29, 2012 at 05:27 PM
Reaction to "Cheap online prescription glasses".
Thanks for your appreciation to my blog.
Of course this blog is about to publish my own expe... Read more»
Archives:
- Playing video and audio with HTML5 July 23, 2010
- Aggregating objects within PHP5 June 26, 2010
- Creating a login system in your website May 05, 2010
- How to Setup your own Webserver May 05, 2010
- Welcome Entry May 05, 2010

United States




