HTML5 Video Codec Selection in JavaScript
I was looking around for a nice video codec selection via JavaScript, and possibly writing my own if I couldn’t find one. Outside of the video players, there isn’t a library either.
It is possible to interrogate the <video> element to find out what codec support it has. The problem is that it is only reliable in Opera. All other browsers are completely unreliable.
But there is an easier solution if all you are trying to do is load the right video via JavaScript. With video selection being an option within the video tag itself, you just need to create the <video><source/><source/></video> via JavaScript. Assuming your video files are encoded correctly (and the server is sending back the right mime types) you’re set!
// Takes a file with no extension, and
// creates a video element for webm/h264/ogg
// and plays it
function createVideo(fileNoExt)
{
var newVid = document.createElement(‘video’);
// IE, Safari, IOS
var h264 = document.createElement(‘source’);
h264.setAttribute(‘src’, fileNoExt+’.mp4′);
h264.setAttribute(‘type’, ‘video/mp4′);// Firefox
var ogv = document.createElement(‘source’);
ogv.setAttribute(‘src’, fileNoExt+’.ogv’);
ogv.setAttribute(‘type’, ‘video/ogg’);// Chrome
var webm = document.createElement(‘source’);
webm.setAttribute(‘src’, fileNoExt+’.webm’);
webm.setAttribute(‘type’, ‘video/webm’);newVid.appendChild(webm);
newVid.appendChild(h264);
newVid.appendChild(ogv);document.body.appendChild(newVid);
newVid.play();
}
I’ve been using this approach for a few things, and it seems to work every time.
NOTE: The order of source elements is important. iOS 3.x has a bug where it only looks for the first element, so H.264 should always go first.










