The HTML <audio>
tag is used to embed audio content, such as music, sound effects, or podcasts, into a web page. It provides a way to play audio files directly within the browser without the need for external media players. Here's a breakdown of its basic usage and common attributes:
Basic Syntax:
<audio src="audio.mp3" controls></audio>
Attributes:
src: Specifies the source URL or file path of the audio file.
controls: Adds playback controls (play/pause, volume, seek bar, etc.) to the audio player.
autoplay: Specifies that the audio should automatically start playing when the page loads.
loop: Enables continuous looping of the audio.
muted: Sets the audio to be initially muted.
preload: Defines how the browser should preload the audio file. Possible values are
"none"
,"metadata"
, or"auto"
.volume: Sets the initial volume of the audio, ranging from
0.0
(silent) to1.0
(maximum volume).
Example Usage:
<audio src="audio.mp3" controls></audio>
Multiple Audio Sources: Similar to videos, you can provide multiple audio formats using <source>
tags within the <audio>
tag to ensure broader browser compatibility.
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="audio.ogg" type="audio/ogg">
Your browser does not support the audio tag.
</audio>
Audio Playback with JavaScript: You can control audio playback programmatically using JavaScript by accessing the <audio>
element through its ID or other means. This allows you to customize the behavior, such as implementing custom controls or triggering specific actions based on user interactions.
<audio id="myAudio" src="audio.mp3"></audio>
<button onclick="playAudio()">Play</button>
<button onclick="pauseAudio()">Pause</button>
<script>
var audio = document.getElementById("myAudio");
function playAudio() {
audio.play();
}
function pauseAudio() {
audio.pause();
}
</script>
These are the key aspects of using the <audio>
tag in HTML. Remember to provide multiple audio formats for wider browser compatibility and consider incorporating accessibility features like captions or alternative text when appropriate.