The HTML <audio>
tag is a tag released in HTML5 as a way to embed a music file directly to your HTML document.
Before the release of the <audio>
tag, you need to embed music files using flash or third-party websites such as SoundCloud.
With the <audio>
tag, embedding a music file is as easy as adding the following code snippet to your HTML document:
<audio controls>
<source src="sound.ogg" type="audio/ogg" />
<source src="sound.mp3" type="audio/mpeg" />
Your browser does not support the audio tag.
</audio>
The output of the above tag will be as follows:
To work properly, the <audio>
tag requires you to add at least one <source>
tag as the source of the embedded audio file.
When you have more than one source, then the browser will pick the first format that it can play.
When none of the format is supported by the browser, then the text “Your browser does not support the audio tag.” will be displayed on the browser.
Currently, HTML supports the following audio formats:
- MP3
- WAV
- and OGG format
The controls
boolean attribute inside the <audio>
tag is used to display the play/pause
button, the progress bar, and the volume button.
Without specifying the controls
attribute, the <audio>
tag won’t render anything in the browser.
You can also automatically play the audio file once it has been loaded to the page by specifying the autoplay
attribute:
<audio controls autoplay>
<source src="sound.mp3" type="audio/mpeg" />
Your browser does not support the audio tag.
</audio>
The full list of boolean attributes supported by the <audio>
tag is as shown below:
controls
- used for displaying interactive control in the browserautoplay
- play the audio file once loadedloop
- repeat the audio file as long as the page is opened in the browsermuted
- Initially mute the audio file
Boolean attributes are active without any value, so you just need to write the attribute for it to take effect.