HTML <audio> Tag
The <audio> tag is one of the HTML5 elements added to allow embedding audio files into a web page. Since not all browsers support all audio formats, the audio file is encoded using special codecs.
The <source> tag or the src attribute is used to indicate the variations of the same audio file. The path to an audio file can contain absolute or relative URLs.
Syntax
The <audio> tag comes in pairs. The content is written between the opening (<audio>) and closing (</audio>) tags.
HTML <audio> Tag
<audio>
<source src="URL">
<source src="URL">
</audio>Example of the HTML <audio> tag:
Example of the HTML <audio> tag:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<audio controls>
<source src="https://www.w3docs.com/build/audios/jingle_bells.ogg" type="audio/ogg" />
<source src="https://www.w3docs.com/build/audios/audio.mp3" type="audio/mpeg" />
</audio>
<p>Click the play button</p>
</body>
</html>The Loop Attribute
Using the loop attribute will make the audio file play over and over again:
HTML <audio> Tag
<audio src="audio.mp3" autoplay loop></audio>Displaying Browser Controls
You can let the browser display controls to the user, such as volume or play/pause. It is done with the help of the controls attribute.
Displaying Browser Controls code
<audio src="audio.mp3" controls></audio>Example of the HTML <audio> tag with the controls attribute:
Example of the HTML <audio> tag with the controls attribute
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<audio controls src="https://www.w3docs.com/build/audios/audio.mp3">
Your browser does not support the audio element.
</audio>
<p>Click the play button</p>
</body>
</html>Several File Formats
With the <audio> tag you can define multiple formats of the same audio file.
Several File Formats example
<audio controls>
<source src="audio.ogg">
<source src="audio.mp3">
</audio>Attributes
The <audio> tag has attributes that indicate the path to the audio file, playback behavior, etc. The controls, autoplay, loop, and muted attributes are boolean; their values can be omitted. If specified, the corresponding function is enabled by default.
| Attribute | Value | Definition |
|---|---|---|
| autoplay | Plays the audio file automatically after loading the page. | |
| controls | Displays the control panel (play/pause, volume, etc.). If the controls attribute is missing, the audio will not be visible on the page. | |
| loop | Repeats the audio file continuously from the beginning after it finishes. | |
| muted | Mutes the audio by default. | |
| preload | auto, metadata, none | Defines the preloading strategy for the audio file. |
| src | URL | Specifies the path to the audio file. |
The <audio> tag supports the Global Attributes and the Event Attributes.
Practice
What are the properties of the HTML audio tag?