The HTML 5 Audio Element

1:08:00 PM |

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

  1. <audio autoplay="autoplay" controls="controls">  
  2.     <source src="file.ogg" />  
  3.     <source src="file.mp3" />  
  4. </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

  1. // Slightly modified from video version.  
  2. $(document).ready(function() {  
  3.     // Create an audio element, and set it to autoplay,  
  4.    // and show the player when the page loads.  
  5.     var audio = $('<audio>', {  
  6.       autoPlay : 'autoplay',  
  7.       controls : 'controls'  
  8.     });  
  9.   
  10.     // Call our addSource function, and pass in the audio element  
  11.     // and the path(s) to your audio.  
  12.     addSource(audio, 'audioFile.ogg');  
  13.     addSource(audio, 'audioFile.mp3');  
  14.   
  15.     // When some event is fired...  
  16.     $('a').click(function() {  
  17.      // Add the audio + source elements to the page.  
  18.       audio.appendTo('body');  
  19.       // Fadeout the anchor tag to keep the user from clicking it again.  
  20.       $(this).fadeOut('slow');  
  21.       return false;  
  22.     });  
  23.   
  24.    // Adds a source element, and appends it to the audio element, represented  
  25.    // by elem.  
  26.     function addSource(elem, path) {  
  27.       $('<source>').attr('src', path).appendTo(elem);  
  28.     }  
  29.   
  30. });  
  31. </audio>