HTML Audio
HTML Audio element <audio>
can be used to include audio into an HTML document.
We just need the below details to include an audio file.
- Audio file source location and its format
- Text to display instead of audio in case the browser does not support
<audio>
element
<audio controls>
<source src="/assets/audios/music.mp3" type="audio/mpeg">
Oops!! Your browser does not support audio element.
</audio>
HTML Audio - Supported Formats
HTML audio element supports only three audio formats as mentioned below.
- MP3 videos with type = audio/mpeg
- WAV videos with type = audio/wav
- OGG videos with type = audio/ogg
HTML Audio - Multiple Sources
In case, if we have different formats of the same audio, then all those formats can be provided within the same <audio>
element as shown below.
The browser will pick up the first recognizable format.
<audio controls>
<source src="/assets/audios/music.mp3" type="audio/mpeg">
<source src="/assets/audios/music.wav" type="audio/wav">
<source src="/assets/audios/music.ogg" type="audio/ogg">
Oops!! Your browser does not support audio element.
</audio>
HTML Audio Attributes
Here is the list of attributes that audio can have on an HTML document.
- Attribute
controls
to display audio controls like play, pause, volume, download, and playback speed options - Attribute
autoplay
to automatically start playing audio upon page load - Attribute
muted
to mute audio upon page load
<audio controls autoplay muted>
<source src="/assets/audios/music.mp3" type="audio/mpeg">
<source src="/assets/audios/music.wav" type="audio/wav">
<source src="/assets/audios/music.ogg" type="audio/ogg">
Oops!! Your browser does not support audio element.
</audio>
Example
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1>HTML Audio</h1>
<audio controls>
<source src="/assets/audios/music.mp3" type="audio/mpeg">
<source src="/assets/audios/music.wav" type="audio/wav">
<source src="/assets/audios/music.ogg" type="audio/ogg">
Oops!! Your browser does not support audio element.
</audio>
</body>
</html>
Overall
HTML Audio element <audio>
makes it easy to add an audio file to an HTML document.