The `<audio>` tag in HTML is used to embed sound content in documents. It can be used to play audio files such as music, speeches, or sound effects. The `<audio>` element supports multiple audio formats, including MP3, WAV, and Ogg. Here’s a basic example of how to use the `<audio>` tag:
<audio controls>
<source src="audio-file.mp3" type="audio/mpeg">
<source src="audio-file.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
Attributes of the `<audio>` Tag
controls: Adds audio controls, like play, pause, and volume.
autoplay: Specifies that the audio will start playing as soon as it is ready.
loop: Specifies that the audio will start over again, every time it is finished.
muted: Specifies that the audio output should be muted.
preload: Specifies if and how the author thinks the audio should be loaded when the page loads. It can have three values:
auto: The browser should load the entire audio file when the page loads.
metadata: Only metadata (like length) is loaded.
none: The audio file should not be loaded when the page loads.
Example with Attributes
<audio controls autoplay loop muted preload="auto">
<source src="audio-file.mp3" type="audio/mpeg">
<source src="audio-file.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
Handling Unsupported Browsers
If the browser does not support the `<audio>` element, the content inside the `<audio>` tag (e.g., "Your browser does not support the audio element.") will be displayed to the user.
Using JavaScript with `<audio>`
You can manipulate the audio element using JavaScript. Here’s an example:
<audio id="myAudio" controls>
<source src="audio-file.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<button onclick="playAudio()">Play</button>
<button onclick="pauseAudio()">Pause</button>
<script>
function playAudio() {
var audio = document.getElementById("myAudio");
audio.play();
}
function pauseAudio() {
var audio = document.getElementById("myAudio");
audio.pause();
}
</script>
This example adds play and pause buttons that control the audio playback using JavaScript.