How to Play Audio in HTML

Wednesday, February 29, 2012

Adding audio can be just as challenging as adding video to your HTML web pages. Fortunately, with a little help, adding audio content to your HTML pages can be easy. There are several methods of adding audio and each method has its own advantages and disadvantages. There are many different methods that can be used to add media to your pages. Please note that some of the methods listed below are not supported in HTML 4.01. You either have to have a browser that supports HTML 5 or your users will have to install the required plug-ins. Here are the most common ways to add video to your web pages.

Audio Element

The <audio> element is an HTML 5 element. Within the <audio> element, you can add multiple <source> elements so that the browser can choose which file is best to download. Here is an example.

<audio controls="controls">
         <source src="musicFile.mp3" type="audio/mpeg"/>
          <source src="musicFile.ogg" type="audio/ogg"/>
          Text content in the event that no audio can be played.

Embed & Object Elements

You can also use the <embed> and/or <object> elements to try to play multimedia elements in HTML pages. Here is an example of how to play audio using both elements. While the <object> element is supported in HTML 4, the <embed> element is not. If the browser does not support the file format, the audio will not play. Using this method is not easy when supporting various types of browsers.

<embed src="musicFile.mp3" height="50" width="250"/>
<object data="musicFile.mp3" height="50" width="250"/>

Use Multiple Solutions

Another method is to use various elements so that at least one method is likely to be supported by the user's browser. Keep in mind that this option includes HTML 4 and HTML 5 elements. For your page to validate correctly, you will need to use the HTML 5 DOCTYPE, <!DOCTYPE html>. In this example, the browser will attempt to play the audio using one of the elements in this order: audio, object, then embed. Here is an example.

<audio controls="controls">
  <source src="musicFile.mp3" type="audio/mpeg" />
  <source src="musicFile.ogg" type="audio/ogg" />
  <object data="musicFile.mp3" height="50" width="250">
     <embed src="musicFile.mp3" height="50" width="250">
        Text content in the event that no audio can be played.

Again, my suggestion is to implement an audio solution that is easy to maintain while still providing meeting the needs of your users.

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

HTML CSS and JavaScript Editor Creating Web Pages Simplified HTML CSS: The Complete Reference