Advertisement

Quick Tip: The HTML 5 Audio Element

by

This Cyber Monday Tuts+ courses will be reduced to just $3 (usually $15). Don't miss out.

As of Firefox 3.5, Chrome 3, Opera 10.5, and Safari 4, we can take advantage of many of the new HTML 5 features, including native audio support without the need for Flash. As you'll find, we only to create the new <audio> element, and set a few attributes. In this four minute video quick tip, we'll review the mark-up, and also a quick way to play audio with jQuery.


The Audio Element

<audio autoplay="autoplay" controls="controls">
	<source src="file.ogg" />
	<source src="file.mp3" />		
</audio>

The audio element accepts a handful of attributes, most notably:

  • autoplay : Immediately plays the file when the page loads.
  • controls : Displays the player on the page.
  • preload : Immediately begins buffering the file. (values = none, auto, metadata)
  • src : The path to the file name. It's a better practice to load the file via the child "source" element instead.

Mozilla and Webkit don't fully get along just yet, when it comes to the audio format. Firefox will want to see an .ogg file, while Webkit browsers will work just fine with the common .mp3 extension. This means that, at least for now, you should create two versions of the audio. I recommend that you use a quick and simple online tool, called Media.io, to convert your mp3 over to the ogg format.

When Safari loads the page, it won't recognize that .ogg format, and will skip it and move on to the mp3 version, accordingly. Please note that IE, per usual, doesn't support this, and Opera 10 and lower can only work with .wav files.


Loading Audio with jQuery

// Slightly modified from video version.
$(document).ready(function() {
    // Create an audio element, and set it to autoplay, 
   // and show the player when the page loads.
    var audio = $('<audio />', {
      autoPlay : 'autoplay',
      controls : 'controls'
    });
    
    // Call our addSource function, and pass in the audio element
    // and the path(s) to your audio.
    addSource(audio, 'audioFile.ogg');
    addSource(audio, 'audioFile.mp3');
  
    // When some event is fired...
    $('a').click(function() {
     // Add the audio + source elements to the page.
      audio.appendTo('body');  
      // Fadeout the anchor tag to keep the user from clicking it again.
      $(this).fadeOut('slow');
      return false;
    });
    
   // Adds a source element, and appends it to the audio element, represented 
   // by elem.
    function addSource(elem, path) {
      $('<source />').attr('src', path).appendTo(elem);
    }
   
});

Please note that we can go much, much further with this, including how to stop the audio, change the volume, etc. This quick three minute tip is just to whet your appetite. If you'd like to delve deeper, let us know and I'll schedule a full thirty-minute tutorial on the topic!

Advertisement