Skip to main content

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> and controls
  • 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​

index.html
<audio controls src="episode-12.mp3">
Your browser cannot play this audio.
<a href="episode-12.mp3">Download the episode</a>.
</audio>

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:

  1. src names the file, like the src of an image.
  2. controls shows the browser's player. Without it, nothing appears on the page.
  3. 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​

AttributeWhat it doesAdvice
srcThe address of the audio fileOr use source elements for several formats (see Source)
controlsShows the playerAlmost always include it
loopStarts again when it endsOnly with controls, and rarely
mutedStarts with the sound offNeeded for any autoplay attempt
autoplayTries to start by itselfAvoid (see below)
preloadHow much to download early: none, metadata, or autoUse none or metadata to save data
crossoriginHow to fetch a file from another siteNeeded for some features, such as analysing the sound

preload​

ValueMeaningGood for
noneDownload nothing until the visitor presses playA page with many players
metadataDownload only the length and basic detailsThe usual choice
autoLet the browser download as it likes, often the whole fileA 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.

index.html
<!-- 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:

FormatTypical fileNotes
MP3.mp3The safest choice. Plays almost everywhere, with good quality at modest size
AAC.m4a, .aacGood quality at small size, widely supported
Ogg Vorbis or Opus.ogg, .opusEfficient and free of licences. Support varies by browser, so check before relying on it
WAV.wavUncompressed, so files are large. Good for short sound effects
FLAC.flacLossless 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.

Keep files small

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, or aria-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 lang if 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" or metadata, 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​

  1. Leaving out controls.
  2. Using autoplay, especially with sound.
  3. Looping music that cannot be stopped.
  4. No fallback content or download link.
  5. No transcript.
  6. A huge uncompressed WAV for a long recording.
  7. Using only a format some browsers cannot play, and not testing.
  8. preload="auto" on a page with many players, which downloads them all.
  9. Not handling the rejected promise from play().
  10. Assuming the audio is private because the player is hidden.
  11. Using sound alone to show an error or a success.
  12. 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:

  1. Add an <audio controls> element and play it with the keyboard only.
  2. Add fallback text, and a download link.
  3. Try loop, and then remove it again.
  4. Compare preload="none" and preload="auto" in the browser's network panel.
  5. Add autoplay and see what your browser does. Then remove it.
  6. Add a button that calls audio.play(), and handle a rejected promise.
  7. Show the current time in a paragraph, using the timeupdate event.
  8. Add two buttons that jump forward and back by 10 seconds.
  9. Put the audio in a figure with a figcaption.
  10. Bonus: add a transcript in a details widget, 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" or metadata.
  • 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.