Browser

How to use the new HTML5 Audio element

Ryan Boudreaux explains how to use the new HTML5 audio element in websites and includes examples of fallback options.

Several exciting elements to come out of the HTML5 specification include presenting native multimedia content within browsers, and specifically addressing the aspects for providing audio and video content within web pages utilizing a standardized format. The HTML5 audio <audio> element utilizes a standard way of embedding audio digital content, thus allowing web developers the freedom of not having to rely solely on plugins to associate with the content file types. Once enabled and fully implemented as a standard, there will be no requirement for a browser plugin, as the HTML5 specifies a standard way to include audio content with the <audio> elements.  So will these multimedia elements replace Flash?

The audio element in its simplest form is represented as specifying a single source src="url":
<audio src=""></audio>

The audio element offers the option for a control attribute in the form controls="controls" for adding play, pause, and volume controls, as in the example:

<audio src="music.mp3" controls="controls">
</audio>

Attributes

In addition to the source (src="url") and controls (controls="controls") attributes, listed below are the five attributes, their associated values, and a short description:

Table 1

In reference to the "autoplay" attribute, and as a rule of thumb, in most instances new visitors to a website will frown upon any audio instantly playing as they navigate into a website. However, there are some instances when autoplaying audio on websites is acceptable; sites that promote music, a band, a musician, or other aural artistic forms, would probably benefit from autoplaying a sampling of a performance.

The <audio> element can play sound files as well as an audio streaming, and there are three main audio file formats supported for the <audio> element:

  • Ogg - with the extension .ogg and called "Vorbis"
  • MP3 -
  • Wav -

As a best practice, it is advisable to insert fallback statement content between the <audio> and </audio> tags for browsers that do not support the audio element (more examples of fallback support will be provided below):

<audio src=" music.mp3" controls="controls">
Your browser does not support the HTML5 audio element.
</audio>

Browser support for <audio> element

Currently the listed browsers support the following audio file codec and formats as listed in the matrix below:

Table 2

This is an example of a single audio source from the Internet Archives.org of a Roy Rogers radio show "The Horse Thieves of Paradise Valley":

<audio src="http://ia700204.us.archive.org/13/items/The_Roy_Rogers_Show/Roy_Rogers_480905_Horse_Thieves_of_Paradise_Valley.mp3"
controls="controls">Your browser does not support the HTML5 audio element.
 </audio>

The code above rendered in an HTML5 supported browser:

(Note: Play the actual audio file via the player at the top of the post.)

Sources

Solving the cross-browser functionality issue, you can list several sources for the audio clip as long as there is more than one file type available. Browsers will attempt to load the source file in the coded order, and if the file fails to load, the browser will move onto the next source within the <audio> element. The example below shows how a single audio can be rendered in several browsers by providing the two file format sources, in this instance .ogg and mp3:

    <section>
        <h1>HTML5 Audio Element</h1>
        <h2>The Roy Rogers Show</h2>
        <h3 align="left">Horse Thieves of Paradise Valley</h3>
        <audio controls="controls">
        Your browser does not support the audio element.
            <source src="http://ia700204.us.archive.org/13/items/The_Roy_Rogers_Show/Roy_Rogers_480905_Horse_Thieves_of_Paradise_Valley.mp3" type="audio/mp3" /></source>
            <source src="http://.../audio/Roy_Rogers_480905_Horse_Thieves_of_Paradise_Valley.ogg" type="audio/ogg" /></source>
        </audio>
    </section>

The resulting code as displayed in Firefox 3.6 browser:

Figure A

Another example of providing fallback support:

    <!-- The browser will automatically choose the format it supports. -->
    <audio controls="controls">
        <source src="audio.mp3" type="audio/mp3">
        <source src="audio.ogg" type="audio/ogg">
        <source src="audio.aac" type="audio/mp4">
        <!-- If no support at all. -->
        Your browser does not support the HTML5 audio element.
    </audio>

Cross-browser support and fallback

If the selected browser does not render the .mp3, .wav, or the .ogg file format, then you could add another fallback allowing Flash to play the file. Another option is employing the use of the jPlayer HTML5 Audio Checker which tests browsers for HTML5 <audio> element support and for Audio() object support using "feature sniffing" utilizing JQuery and JavaScript to check for audio element support.

The specification also allows the use of enhanced audio API features to directly generate and manipulate audio streams from JavaScript code; several controls using the API extensions include:

  • play() - plays the audio
  • pause() - pauses the audio
  • canPlayType() - examines the browser to establish whether the given mime type can be played
  • buffered() - attribute that specifies the start and end time of the buffered part of the file

An example of JavaScript calling and playing audio:

// Call and play audio via JavaScript
$(document).ready(function() {
       var audioElement = document.createElement('audio');
       audioElement.setAttribute('src', ‘audio_file.ogg');
       audioElement.load()
       audioElement.addEventListener("load", function() {
               audioElement.play();
               $(".duration span").html(audioElement.duration);
               $(".filename span").html(audioElement.src);
       }, true);
       $('.play').click(function() {
               audioElement.play();
       });

An example of JavaScript to pause the audio:

       $('.pause').click(function() {
               audioElement.pause();
       });

Determining what format the browser will use with JavaScript code is a little more complex than the simple fallback model for the <audio> element source. Using the canPlayType() API method to pretest the browser's file format capabilities, it takes an audio mime type, and codec (optional) parameters, and returns one of three strings: empty, maybe, or probably.

The following JavaScript code example tests for three file types .mp3, .ogg, and .aac audio file formats:

  <script>
 function checkAudioCompat() {x
       var myAudio = document.createElement('audio');
      if (myAudio.canPlayType) {
          // CanPlayType returns maybe, probably, or an empty string.
          if ( "" != myAudio.canPlayType('audio/mpeg')) {
              alert("mp3 supported");
          }
          if ( "" != myAudio.canPlayType('audio/ogg; codecs="vorbis"')) {
              alert("ogg supported");
          }
         if ( "" != myAudio.canPlayType('audio/mp4; codecs="mp4a.40.5"')) {
              alert("aac supported");
          }
      }
      else {
         alert("no audio support");
      }
  }
</script>

Because the canPlayType() API can return more than one audio file format, it might be a good practice to test for hierarchy, and then choosing the best fit for the file format and browsers used by the customer.

About

Ryan has performed in a broad range of technology support roles for electric-generation utilities, including nuclear power plants, and for the telecommunications industry. He has worked in web development for the restaurant industry and the Federal g...

0 comments

Editor's Picks