HTML 5 audio & video elements

03 Apr 2009 by David Corvoysier

One of the most revolutionary concept introduced by HTML 5 is the native support of audio and video playback in web pages.

Two new HTML elements have been defined for that purpose: audio and video, based on the generic media element type.

Media elements use a common set of attributes:

  • src: defines the source of the media to render,
  • autoplay: boolean to activate|prevent immediate playback,
  • loop: boolean to activate|prevent automatic looping on content,
  • controls: boolean to display|hide browser playback user interface.

video and audio elements can contain elements to be displayed to the user in older browsers that do not support these new elements.

Below is an example of how to use the element:

<audio src="audio.ogv" controls width="100" height="50">
    <a href="audio.ogv">Listen</a>
</audio>

Alternatively to the src attribute, the content to be rendered can be specified using one or more elements, each of them describing a specific media resource.

Each can be identified by its src and type attributes, optionally complemented by a codecs attribute:

<audio controls width="100" height="50">
     <source src="audio.ogg" type="audio/ogg; codecs=vorbis">
    <source src="audio.spx" type="audio/ogg; codecs=speex">
    <source src="audio.oga" type="audio/ogg; codecs=flac">
</audio>

The video element has an optional poster attribute that can be used to define an image to be displayed before the video is played:

<video src="oggy.ogv" poster="oggy.jpg" />

These new media elements also support a set of handy javascript method, properties and events, to allow the fine-grained control of the rendered UI.

<script>
function playVideo(url){
     var video = document.getElementById("video");
     video.setAttribute("src",url);
}
</script>
<video id="videoPlayer" controls=false/>
<p>
     <button type="button" 
             onclick="video.playbackRate = -2;">
         Rew
     </button>
     <button type="button" 
             onclick="video.play();">
         Play
     </button>
     <button type="button" 
             onclick="video.pause();">
         Pause
     </button>
     <button type="button" 
                 onclick="video.playbackRate = 2;">
         FF
     </button>
</p>
comments powered by Disqus