HTML5 Audio Tag

You can play any audio file with the use of different browser plug-ins like MS Windows Media Player, Adobe Flash Player, Apple Quick Time etc. But now HTML5 has made it very simple. With HTML5 supporting <audio> tag, you can play any audio file in any browser without the use of any plug-in.

HTML5 uses <audio> tag for embedding audio in HTML file. You can generally use audio formats like mp3, wav, ogg Vorbis, AAC which are supported by different web browsers. You can incorporate these varied audio formats to HTML using <source> tag and the browser will use the format it recognises first and will run the audio file.

Syntax

<audio controls autoplay>
<source src="song.mp3" type="audio/mpeg">
<source src="song.wav" type="audio/wav">
<source src="song.ogg" type="audio/ogg">
</audio>

HTML5 Audio Tag Example

<!DOCTYPE HTML>  
<html>  
<head>  
    <meta charset=UTF-8" />  
    <title>HTML5 Audio Element Example</title>  
</head>  
<body bgcolor="#fvvyee">
<audio controls autoplay>
<source src="song.mp3" type="audio/mpeg"/>
<source src="song.wav" type="audio/wav"/>
<source src="song.ogg" type="audio/ogg"/>
</audio>
</body>
</html>

This will produce following result

In above example, src is the URL of your audio file. Providing MIME type i.e. type="audio/mpeg" is optional but it is good to provide it for faster working of the browser. With the use of autoplay, the browser will play the audio file without asking for visitor's permission.

As of writing, only few browsers provide support for this new feature.

Browser Supports

Audio Attributes

AttributesValueDescription
controlsBoolean attributeThis is used to make the native audio player appear.
autoplayBoolean attributeThis is used to automatically play an audio clip.
loopBoolean attributeThis is used to keep repeating your audio clip.
srcurlThis is used to set url of audio clip.
preloadnone | metadata | autoThis is used to set buffering of audio clip :
none - do not buffer audio file automatically.
metadata - only buffer the metadata of audio file.
auto - buffer audio file before it gets played.

Syntax : Controls Attribute

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

Syntax : Autoplay Attribute

<audio controls="true" autoplay="true"/>
<source src="song.mp3" type="audio/mpeg"/>
</audio>

Syntax : Loop Attribute

<audio controls="true" loop="true">
<source src="song.mp3" type="audio/mpeg"/>
</audio>

Syntax : Preload Attribute

<audio preload="none">
<source src="song.mp3" type="audio/mpeg">
</audio>