HTML Audio Element
Sound can make a page feel alive: a podcast episode, a pronunciation guide, a song sample, or a short voice message. The <audio> element adds it with one line of HTML, and the browser supplies a complete player, with play, pause, a progress bar, and volume.
This lesson shows how to add sound well: which attributes to use, which formats to choose, how the autoplay rules work, and how to make audio useful for people who cannot hear it.
What You Will Learnβ
- Adding sound with
<audio>andcontrols - The attributes:
src,controls,loop,muted,preload,autoplay - Choosing a file format
- Fallback content for old browsers
- The autoplay rules, and why to avoid autoplay
- Controlling playback with JavaScript
- Transcripts, accessibility, and global notes
The Basicsβ
- HTML Code
- Browser Output
<audio controls src="episode-12.mp3">
Your browser cannot play this audio.
<a href="episode-12.mp3">Download the episode</a>.
</audio>
Preparing the soundβ¦
paused: truecurrentTime: 0.0 s of 0.0 svolume: 1.00- Latest events: none yet
This sound is generated by the page itself (three short notes), so no file is needed. Press play, drag the bar, change the volume, and watch the values change.
The demo above is a real <audio> element, playing a short sound that the page builds itself. Try the player, and watch the values underneath.
Three things to notice:
srcnames the file, like thesrcof an image.controlsshows the browser's player. Without it, nothing appears on the page.- The text inside is fallback content. A browser that supports
<audio>ignores it, and one that does not shows it. A download link is the most useful fallback.
The player looks different in every browser. That is normal, and each one is already keyboard and screen reader friendly.
Attributesβ
| Attribute | What it does | Advice |
|---|---|---|
src | The address of the audio file | Or use source elements for several formats (see Source) |
controls | Shows the player | Almost always include it |
loop | Starts again when it ends | Only with controls, and rarely |
muted | Starts with the sound off | Needed for any autoplay attempt |
autoplay | Tries to start by itself | Avoid (see below) |
preload | How much to download early: none, metadata, or auto | Use none or metadata to save data |
crossorigin | How to fetch a file from another site | Needed for some features, such as analysing the sound |
preloadβ
| Value | Meaning | Good for |
|---|---|---|
none | Download nothing until the visitor presses play | A page with many players |
metadata | Download only the length and basic details | The usual choice |
auto | Let the browser download as it likes, often the whole file | A single, important track |
preload is a hint, not an order. The browser may ignore it, especially on mobile connections where it tries to save data.
Try It: Build the Tagβ
Change the attributes, and see the HTML and what a careful developer would say.
- HTML Code
- Browser Output
<!-- A polite player -->
<audio src="episode.mp3" controls preload="none"></audio>
<!-- Risky: autoplays, loops, and has no controls -->
<audio src="music.mp3" autoplay loop></audio>
Choosing a Formatβ
A browser plays a file only if it understands its format (the container and the codec inside). Common audio formats:
| Format | Typical file | Notes |
|---|---|---|
| MP3 | .mp3 | The safest choice. Plays almost everywhere, with good quality at modest size |
| AAC | .m4a, .aac | Good quality at small size, widely supported |
| Ogg Vorbis or Opus | .ogg, .opus | Efficient and free of licences. Support varies by browser, so check before relying on it |
| WAV | .wav | Uncompressed, so files are large. Good for short sound effects |
| FLAC | .flac | Lossless and large. Support is common now, but check |
For most websites, one MP3 or AAC file is enough. If you need to be sure, offer two formats with <source>, and let the browser choose. See Source.
Format support can change over time, so test in the browsers your visitors use.
Speech does not need music quality. A podcast episode at a lower bitrate sounds fine and loads much faster, which matters to visitors on slow or expensive connections.
Autoplay: Please Don'tβ
autoplay asks the browser to start playing as soon as it can. It sounds convenient, but:
- Most browsers block it when the audio has sound, unless the visitor has already interacted with the page. The attribute silently does nothing.
- When it does work, it startles people, clashes with screen reader speech, and annoys anyone in a quiet place.
- It wastes data for visitors who never wanted the sound.
If you really need sound after a click, start it from the click handler:
document.getElementById("start").addEventListener("click", () => {
document.getElementById("sound").play();
});
A click counts as the visitor's request, so the browser allows it.
Controlling Audio with JavaScriptβ
Every <audio> element has a built-in API:
const audio = document.querySelector("audio");
audio.play(); // returns a Promise
audio.pause();
audio.currentTime = 30; // jump to 30 seconds
audio.volume = 0.5; // 0 (silent) to 1 (full)
audio.playbackRate = 1.5; // faster
audio.muted = true;
audio.addEventListener("ended", () => console.log("Finished"));
play() returns a promise, which fails if the browser blocks the sound. Always handle that:
audio.play().catch((error) => {
console.log("Playback was blocked:", error.name);
// Show a visible "Play" button instead
});
The useful events are loadedmetadata, play, pause, ended, timeupdate, volumechange, and error. You saw some of them in the demo's event list. Building your own controls is covered in Media Controls.
Transcripts: Sound for Everyoneβ
An audio file is invisible to search engines, to people who cannot hear it, and to anyone in a place where they cannot play it. A transcript (the words, written down) fixes all of that.
<figure>
<figcaption>Episode 12: Why bread rises</figcaption>
<audio controls src="episode-12.mp3"></audio>
</figure>
<details>
<summary>Read the transcript</summary>
<p><strong>Asha:</strong> Welcome back to the showβ¦</p>
</details>
- Put the transcript on the same page, or link to it right next to the player.
- Include who is speaking and meaningful sounds, such as "[laughter]".
- Use a details and summary widget if the text is long, so it does not take over the page.
- Captions with
<track>are for video. For audio-only content, a transcript is the standard way. See Accessible Media.
Accessibility at a Glanceβ
- Always provide
controls, or your own accessible controls. - Never autoplay sound, and never play sound that cannot be paused.
- Add a transcript for speech, and describe important non-speech sounds.
- Label the player with a nearby heading or
figcaption, oraria-label="Episode 12". - Do not rely on sound alone for instructions or errors. Add a visual message.
- Keep the sound reasonable. Avoid sudden loud sounds.
- Test with the keyboard: the player must be reachable with Tab, and Space must play and pause.
Security and Privacy Notesβ
- Audio files can always be downloaded. Do not rely on hiding the player, or on a "no download" setting, to protect them. If sound must be private, serve it only to signed-in users, on the server.
- Own the rights. Music, voice recordings, and sound effects are usually protected by copyright.
- Use HTTPS. An insecure audio file on a secure page can be blocked as mixed content.
- Be careful with user-uploaded audio. Check the file type and size on the server, and never use the file name straight in HTML. Escape it first.
- Third-party players can load trackers. Check what an embed loads before adding it, and ask for consent where required.
Global Audience Notesβ
- Provide a transcript in the language of the audio, and a translation where you can, so non-native listeners can read along.
- Mark the language of the transcript with
langif it differs from the page. - Offer slower playback. The built-in player often has a speed menu, which helps language learners.
- Think about data costs. Use
preload="none"ormetadata, compress files, and tell people the size ("Download, 12 MB"). - Be careful with idioms and humour in audio, which translate badly, and add clarity in the transcript.
- Respect quiet spaces. Many people read in public places, so sound must always be the visitor's choice.
Common Mistakes to Avoidβ
- Leaving out
controls. - Using
autoplay, especially with sound. - Looping music that cannot be stopped.
- No fallback content or download link.
- No transcript.
- A huge uncompressed WAV for a long recording.
- Using only a format some browsers cannot play, and not testing.
preload="auto"on a page with many players, which downloads them all.- Not handling the rejected promise from
play(). - Assuming the audio is private because the player is hidden.
- Using sound alone to show an error or a success.
- No label to say what the audio is.
Practice Timeβ
Try these in your editor, with any short MP3 you have the right to use:
- Add an
<audio controls>element and play it with the keyboard only. - Add fallback text, and a download link.
- Try
loop, and then remove it again. - Compare
preload="none"andpreload="auto"in the browser's network panel. - Add
autoplayand see what your browser does. Then remove it. - Add a button that calls
audio.play(), and handle a rejected promise. - Show the current time in a paragraph, using the
timeupdateevent. - Add two buttons that jump forward and back by 10 seconds.
- Put the audio in a
figurewith afigcaption. - Bonus: add a transcript in a
detailswidget, with speaker names.
Quick Recapβ
Click a question to check your answer.
1. What does the controls attribute do?
It shows the browser's built-in player (play, pause, progress, and volume). Without it, the audio is invisible and the visitor cannot start it.
2. What is the text inside the audio element for?
It is fallback content, shown only by browsers that cannot play audio. A download link is a good fallback.
3. Why avoid autoplay?
Browsers usually block autoplay with sound, and when it works it startles people and clashes with screen readers. Let the visitor choose to play.
4. What does preload do?
It hints how much to download before the visitor presses play: none, metadata, or auto. Use none or metadata to save data.
5. Which format is the safest choice?
MP3 (or AAC) plays almost everywhere. For extra certainty, offer two formats with source.
6. How do you make audio accessible to people who cannot hear it?
Provide a transcript on the page, with speakers named and important sounds described. It also helps search engines and people who cannot play sound.
Key Takeawaysβ
<audio controls src="β¦">adds a full, accessible player with one line of HTML.- Always include
controls, and give a fallback with a download link. - Choose MP3 or AAC for safety, keep files small, and use
preload="none"ormetadata. - Do not autoplay. Start sound only from a visitor's action, and handle the promise from
play(). - Use the JavaScript API (
play,pause,currentTime,volume, events) for custom behaviour. - Add a transcript for every piece of speech.
- Hidden audio is not private, and embedded players can track visitors.
- Plan for slow connections, many languages, and quiet places.
Next, add moving pictures in Video, or return to the Audio and Video overview.