Audio Integration
By the end of this lesson you will add audio to a page with the <audio> element, offer more than one file format, control how much downloads in advance, understand why browsers block autoplay, write transcripts, and build your own play and pause button.
<audio> shares many attributes with <video> from Video Integration. This lesson focuses on sound: podcasts, lectures and pronunciation guides.
Step 1: a basic audio player
Here is a lecture recording for a college website, with a transcript under it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Lecture audio</title>
</head>
<body>
<h1>Lecture 4: Photosynthesis</h1>
<p>Recorded by Meera Iyer, Biology department, Kochi.</p>
<audio controls preload="metadata" src="audio/lecture-4.mp3">
<a href="audio/lecture-4.mp3">Download lecture 4 (MP3, 22 MB)</a>
</audio>
<details>
<summary>Read the transcript</summary>
<p>Good morning, everyone. Today we will see how plants make their own food from sunlight, water and carbon dioxide...</p>
</details>
</body>
</html>You should see the browser's player with a play button, time and volume. Here it may look greyed out or show 0:00, because the file does not exist.
What each part does:
controlsshows the browser's built-in player. Without it, an<audio>element is not shown on the page at all; browsers hide it completely.srcpoints to one file; Step 2 uses<source>elements for several.- The link inside is fallback content. Only a browser that cannot handle
<audio>shows it. <details>keeps a long transcript tidy until the reader opens it.
Step 2: offer more than one format
An audio file has a container (the file type, such as WebM) and a codec (how the sound is compressed). Think of a tiffin box and the food inside: the browser must open the box and eat the food.
| Format | File | MIME type | Notes |
|---|---|---|---|
| MP3 | .mp3 | audio/mpeg | Plays in every current browser; the safe fallback |
| AAC | .m4a | audio/mp4 | Common from phones and podcast tools |
| Opus | .webm or .ogg | audio/webm; codecs=opus | Very good quality for small files, great for speech |
| WAV | .wav | audio/wav | Uncompressed and huge; avoid on the web |
List the smaller modern file first and MP3 last. The browser plays the first <source> it supports, and type lets it skip the others without downloading them.
<audio controls preload="none">
<source src="audio/episode-7.webm" type="audio/webm; codecs=opus">
<source src="audio/episode-7.mp3" type="audio/mpeg">
<a href="audio/episode-7.mp3">Download episode 7 (MP3)</a>
</audio>JavaScript can ask the browser which formats it supports with canPlayType(). It answers "probably", "maybe" or an empty string for "no". Run this to see your own browser's answers:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Audio format check</title>
</head>
<body>
<h1>Which audio formats can this browser play?</h1>
<ul id="results"></ul>
<script>
const tester = document.createElement("audio");
const formats = ["audio/mpeg", "audio/mp4", "audio/webm; codecs=opus", "audio/wav", "audio/x-made-up"];
const list = document.querySelector("#results");
for (const type of formats) {
const answer = tester.canPlayType(type) || "no";
const item = document.createElement("li");
item.textContent = `${type}: ${answer}`;
list.append(item);
}
</script>
</body>
</html>You should see "probably" or "maybe" for the real formats and "no" for the made-up one. Answers differ between browsers, which is why you list a fallback.
preload and your visitor's data
preload is a hint about how much to fetch before the visitor presses play. none fetches nothing, metadata fetches only details such as the length, and auto allows the whole file. If you leave it out, each browser decides for itself.
A podcast page with 20 episodes and preload="auto" could download hundreds of megabytes nobody asked for. Use none for lists of recordings and metadata for a single recording, so the duration shows.
Autoplay rules
Imagine a news site that starts shouting on a quiet train. Browsers block this: sound may not start by itself until the visitor has interacted with the page, for example by tapping. Each browser adds its own rules, so never rely on autoplay.
In JavaScript, play() returns a promise: a value that tells you later whether the action worked. If the browser blocks playback, the promise is rejected with an error named NotAllowedError, so always handle it:
const music = document.querySelector("#welcome-music");
music.play().catch((error) => {
// Blocked or failed: show a play button instead of forcing sound
console.log(`Autoplay did not start: ${error.name}`);
});WCAG, the main web accessibility guideline, agrees: if audio plays automatically for more than three seconds, users must be able to pause or stop it, or change its volume separately. Self-starting sound also talks over screen readers. Let the visitor press play.
Captions and transcripts for audio
For video, captions run on screen with the <track> element. For <audio>, browsers have no picture area, so they do not display caption text. The answer is a transcript: the full text of what is said, plus important sounds such as "[applause]".
A transcript helps deaf visitors, people in noisy places, fast readers and search engines. WCAG asks for a text alternative for recorded audio-only content. Put it on the same page or link to it next to the player.
Podcast episode pages
A podcast is a series of audio episodes. Each episode deserves its own page with a clear structure:
<article>
<h2>Episode 12: How Kabir got his first web developer job</h2>
<p>Kabir from Jaipur shares how he built three projects and prepared for interviews. 32 minutes.</p>
<audio controls preload="none">
<source src="audio/ep12.webm" type="audio/webm; codecs=opus">
<source src="audio/ep12.mp3" type="audio/mpeg">
</audio>
<p><a href="audio/ep12.mp3" download>Download episode 12 (MP3, 30 MB)</a></p>
<h3>Transcript</h3>
<p><b>Host:</b> Welcome back. Today Kabir is with us from Jaipur...</p>
</article>The download attribute asks the browser to save the file. Podcast apps find episodes through an RSS feed, an XML file where each episode has an <enclosure> element with the audio address, size and type. The page is for people; the feed is for apps.
Step 3: your own play and pause button
Sometimes you want a player that matches your design, such as a single button for a pronunciation guide. The <audio> element has a JavaScript API for this: play(), pause() and the paused property, which is true when nothing is playing.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Custom audio button</title>
</head>
<body>
<h1>Learn to say "Namaste"</h1>
<audio id="clip" preload="none" src="audio/namaste.mp3"></audio>
<button id="toggle" type="button">Play</button>
<p id="status" role="status">Press Play to listen.</p>
<script>
const clip = document.querySelector("#clip");
const toggle = document.querySelector("#toggle");
const status = document.querySelector("#status");
toggle.addEventListener("click", async () => {
if (!clip.paused) {
clip.pause();
toggle.textContent = "Play";
status.textContent = "Paused.";
return;
}
try {
await clip.play();
toggle.textContent = "Pause";
status.textContent = "Playing...";
} catch (error) {
clip.pause();
status.textContent = `Could not play (${error.name}). This demo has no audio file.`;
}
});
clip.addEventListener("ended", () => {
toggle.textContent = "Play";
status.textContent = "Finished. Press Play to hear it again.";
});
</script>
</body>
</html>Press the button. Because the file is missing, you should see a message such as "Could not play (NotSupportedError)". With a real file, the button switches between Play and Pause, and ended resets it. role="status" makes screen readers announce each message, and a real <button> works with the keyboard. Other useful properties are currentTime, duration, volume and playbackRate (1.5 for faster lectures).
Common mistakes
- Leaving out
controlswithout your own buttons. The audio is invisible and cannot be played. - Autoplaying sound. Browsers block it, and it disturbs visitors and screen reader users.
- No transcript. Deaf visitors and search engines get nothing from the audio.
preload="auto"on a page full of episodes. It wastes your visitors' data.- Ignoring the promise from
play(). Errors pass silently and the button shows the wrong state.
Interview questions
1. How do you support several audio formats?
Put several <source> elements inside <audio>, each with src and a type, ordered from preferred to fallback, ending with MP3. The browser plays the first supported one and uses type to skip others without downloading them. canPlayType() can check support in JavaScript.
2. Why does audio.play() sometimes fail, and how do you handle it?
Browsers block sound until the user interacts with the page, and playback fails if the file is missing or unsupported. play() returns a promise, so handle it with try...catch or .catch() and show a play button or message.
3. What does the preload attribute do on <audio>?
It hints how much to fetch before playback: none, metadata (duration and basic details) or auto. Browsers may ignore it, and the default without the attribute is up to the browser. Use none on pages with many recordings to save data.
4. How do you make audio content accessible?
Provide a transcript, because browsers do not display captions for <audio>. Avoid autoplay, and build custom controls from real <button> elements that announce state changes.
5. What happens to an <audio> element without the controls attribute?
It is not rendered at all. It can still be played from JavaScript, which is how custom players work.
Key points
<audio controls>shows the browser's player; withoutcontrolsthe element is invisible.- Offer formats with
<source>andtype, preferred first and MP3 last;canPlayType()checks support. - Use
preload="none"for lists of recordings andmetadatafor a single one. - Browsers block autoplay with sound;
play()returns a promise that you must handle. - Browsers do not show captions for audio, so always provide a transcript.
play(),pause(),pausedand theendedevent are enough to build a custom button.
Exercise
Build an episode page for "Chai with Coders", a podcast recorded in Pune. Include a heading with the episode title, a short summary, an audio player with an Opus WebM file and an MP3 fallback that downloads nothing in advance, a download link, and a transcript inside <details>. Then add a "Play at 1.5x" button that sets playbackRate to 1.5 and starts playback, handling the case where playback fails.
Show solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Chai with Coders: Episode 3</title>
</head>
<body>
<article>
<h1>Episode 3: Ananya's first open source contribution</h1>
<p>Ananya explains how she fixed a bug in a library she used every day. 25 minutes.</p>
<audio id="episode" controls preload="none">
<source src="audio/ep3.webm" type="audio/webm; codecs=opus">
<source src="audio/ep3.mp3" type="audio/mpeg">
</audio>
<p><button id="fast" type="button">Play at 1.5x</button></p>
<p id="status" role="status"></p>
<p><a href="audio/ep3.mp3" download>Download episode 3 (MP3, 24 MB)</a></p>
<details>
<summary>Transcript</summary>
<p><b>Host:</b> Welcome to Chai with Coders. Today Ananya joins us from Pune...</p>
</details>
</article>
<script>
const episode = document.querySelector("#episode");
const status = document.querySelector("#status");
document.querySelector("#fast").addEventListener("click", async () => {
episode.playbackRate = 1.5;
try {
await episode.play();
status.textContent = "Playing at 1.5x speed.";
} catch (error) {
status.textContent = `Could not play (${error.name}).`;
}
});
</script>
</body>
</html>The <source> elements put Opus first and MP3 last, and preload="none" saves data. The button sets the speed before calling play() and reports any failure instead of ignoring it.
Quick Quiz
1. What does a browser show for <audio src="talk.mp3"> without controls?
An audio element without controls is not rendered; it can only be played from JavaScript.
2. Which order of <source> elements is best?
The browser uses the first supported source, so list the efficient modern format first and the universal MP3 as the fallback.
3. What does audio.play() return?
Handle the promise with try...catch or .catch() to react when playback cannot start.
4. How should you make a recorded talk accessible?
Browsers do not display captions for <audio>, so a transcript is the text alternative.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
