HTML & CSSEasy
What is the <audio> tag?
<audio> embeds sound in a page, such as podcasts, music or sound effects, with optional built-in controls and the same media API as <video> (play(), pause(), volume, currentTime, events like ended and timeupdate). Without the controls attribute it is invisible, which is useful for sounds you trigger from JavaScript.
Attributes
controls: show the native player.srcor multiple<source>children (e.g. Opus/OGG and MP3 fallback).preload:none,metadataorauto.loop,muted,autoplay(blocked with sound until the user interacts with the page).
Accessibility
- Provide a transcript for speech content such as podcasts (WCAG requires a text alternative for prerecorded audio).
- Never autoplay audio; if any audio plays for more than three seconds, users must be able to pause or mute it.
- Custom players need real
<button>s with labels and keyboard support.
Common patterns
- UI sound effects:
new Audio("click.mp3").play()inside a click handler (user gesture required). - Custom player UI built on the media API, with a
<input type="range">for seeking. - Advanced audio (mixing, effects, visualizers, synthesis): the Web Audio API.
- Media Session API: shows track info and controls on the lock screen and in OS media keys.
Interview tip
Mention that play() returns a promise that rejects if autoplay is blocked; handle it with .catch().
Code example
html
1<style> body { font-family: system-ui; } </style>2<figure>3 <figcaption>Episode 12: Accessible forms (24 min)</figcaption>4 <audio id="a" controls preload="metadata">5 <source src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3" type="audio/mpeg">6 Your browser does not support audio. <a href="episode-12.mp3">Download the episode</a>.7 </audio>8 <a href="#transcript">Read the transcript</a>9</figure>1011<button id="beep">Play sound effect</button>12<p id="status"></p>13<script>14 const a = document.getElementById("a");15 a.addEventListener("ended", () => (document.getElementById("status").textContent = "Finished"));16 document.getElementById("beep").addEventListener("click", async () => {17 try {18 a.currentTime = 0;19 await a.play(); // play() returns a promise20 document.getElementById("status").textContent = "Playing…";21 } catch (err) {22 document.getElementById("status").textContent = "Playback blocked: " + err.name;23 }24 });25</script>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.