Home : Internet : HTML : Audio

HTML5 Audio

HTML5 supports the <audio> element, allowing you to add an audio player to your web page easily without the need for any plugins. In its most basic form the player looks like this:

Note that the default player looks different depending on your browser, so you might like to reload this page in different browsers to see the full range. You can adjust the look of the player using CSS but for now you should just concentrate on getting it working. Begin with the most basic version of the audio element code:

<audio controls="controls"><source src="SoundFile.mp3" type="audio/mpeg" /></audio>

The example above embeds an audio file in the mp3 format. Unfortunately not all browsers support mp3, so it's a good idea to include multiple versions of the file in different formats. You should probably be okay with mp3 and wav but to be completely safe you might like to include ogg as well, like so:

<audio controls="controls">
 <source src="SoundFile.mp3" type="audio/mpeg" />
 <source src="SoundFile.wav" type="audio/wav" />
 <source src="SoundFile.ogg" type="audio/ogg" />
 <p>This content is displayed by browsers that don't recognize the audio element.</p>

Notice that you can add text to be displayed in browsers that don't support the <audio> element at all.

There are a few more attributes you can use, as shown below:

Attribute Description
src The URL of the audio file.
controls Show user controls: Volume, seek, pause/resume playback.
autoplay Play the file automatically (use with caution—most users hate this and you are very likely to lose visitors!)
autobuffer Automatically begin buffering the file, even if autoplay is off.
loop Automatically loop (keep playing over and over).
preload Load the file as soon as the web page has loaded so it's ready to run. You don't need this if autoplay is on.

Example usage:

<audio controls="controls" loop="loop" >
 <source src="SoundFile.mp3" type="audio/mpeg" />
 <source src="SoundFile.wav" type="audio/wav" />
 <source src="SoundFile.ogg" type="audio/ogg" />


Author: ,  Originally published: 2012-08-10