Sunday, 24 June 2012

How to add Audio in HTML5

If you only want sound, and no video, then the new AUDIO tag is the one to use. The HTML is similar to the VIDEO tags, in that you specify a list of audio file formats. For example, take a look at the following code:

<AUDIO>

<SOURCE SRC="your_audio.mp3">
<SOURCE SRC="your_audio.ogg">
<SOURCE SRC="your_audio.wav">

</AUDIO>

Between the two AUDIO tags we have three SOURCE tags like before. This time, however, you don't need any codec information. The browser will try to play the first song on the list above. If the format is not supported, then it will try to play the second song.

You can add some attributes to the AUDIO tag:

AUTOPLAY
LOOP
CONTROLS
PRELOAD

AUTOPLAY takes the value true or false. Setting AUTOPLAY to true means the song would start playing by itself in the browser, which can be annoying. LOOP means that the song will start all over again after it has finished. Again, the values true and false can be used. Using the CONTROLS attribute with a value of true will get you the browser's in-built audio controls. They look like this in Internet Explorer 9:

Audio controls in a browser

The PRELOAD attribute takes three values: none, auto, and metadata. PRELOAD refers to the audio file itself. When you set it to none the browser won't preload the file at all. Set it to auto and the browser will decide for you, whereas a setting of metadata will load things like song title, album, artist, etc.

Here's an example of the AUDIO attributes:

<AUDIO AUTOPLAY ="false" LOOP="false" CONTROLS="true" PRELOAD="auto">

<SOURCE SRC="your_audio.mp3">
<SOURCE SRC="your_audio.ogg">
<SOURCE SRC="your_audio.wav">

</AUDIO>

If you tried the above code in Firefox then the Ogg file format would play, because Firefox doesn't support the MP3 format, due to licensing issues.

For browsers that don't support the AUDIO tag at all, then you can add some text to the above code:

<AUDIO AUTOPLAY ="false" LOOP="false" CONTROLS="true" PRELOAD="auto">

<SOURCE SRC="your_audio.mp3">
<SOURCE SRC="your_audio.ogg">
<SOURCE SRC="your_audio.wav">
YOUR BROWSER DOESN'T SUPPORT THE AUDIO TAG.

</AUDIO>

The point about the AUDIO and VIDEO tags, however, is that they work in the browser and don't need the end-user to download any third-party plugins.

No comments:

Post a Comment