Cross-Browser HTML5 Video With Flash or Silverlight Fall-back
Until recently, playing video files in a web page was notoriously complicated. The user requires a Flash or Silverlight plug-in and even the simplest HTML is a confusing mess:
<object width="320" height="240">
<param name="movie" value="myvideo.swf" />
<embed src="myvideo.swf" width="320" height="240"></embed>
</object>
Few HTML5 features excite developers more than native audio and video. The <audio>
and <video>
tags allow you to play media files in an HTML5-aware browser without a plug-in. The elements also become part of the DOM so you can create your own player controls, add captions and synchronize JavaScript events with media playback. As a bonus, the basic HTML5 code is far easier to understand:
<video src="myvideo.mp4" width="320" height="240" />
The web developer’s life is never that simple, of course. Although the HTML5 specification defines the <audio>
and <video>
tags, it does not specify a particular codec and vendors have their own choices. For IE and Safari, you can’t go wrong with H.264-encoded MP4 files. Firefox, Chrome and Opera support Theora or Vorbis in an Ogg container and WebM will be available soon.
Therefore, you’ll still need to encode multiple files for a single video. Fortunately, there’s no need to resort to scripting or browser detection because HTML5 permits us to define any number of source files — the browser will choose the first compatible format it finds, e.g.
<video width="320" height="240">
<source src="myvideo.mp4" type="video/mp4" />
<source src="myvideo.ogv" type="video/ogg" />
<source src="myvideo.webm" type="video/webm" />
</video>
If the browser doesn’t support the <video>
tag, we can fall back to a Flash or Silverlight version:
<video width="320" height="240">
<source src="myvideo.mp4" type="video/mp4" />
<source src="myvideo.ogv" type="video/ogg" />
<source src="myvideo.webm" type="video/webm" />
<object width="320" height="240">
<param name="movie" value="myvideo.swf" />
<embed src="myvideo.swf" width="320" height="240"></embed>
</object>
</video>
Alternatively, we can display a helpful error message or show an image — perhaps an animated PNG or GIF!
<video width="320" height="240">
<source src="myvideo.mp4" type="video/mp4" />
<source src="myvideo.ogv" type="video/ogg" />
<source src="myvideo.webm" type="video/webm" />
<p>Sorry, your browser cannot play this video.</p>
<img src="videofail.png" />
</video>
This facility was specifically designed in HTML5 so video can be shown on legacy browsers with a plug-in. HTML5 lives very happily with Flash or Silverlight — it won’t kill them off any time soon!