Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 122 Β· Images and Media

Audio

Play sound with the HTML audio element. Add controls, offer MP3 and Ogg sources, understand autoplay rules, loop and mute, and start audio from JavaScript.

Podcasts, music samples, pronunciation guides, sound effects in a game: the web is full of sound. HTML plays it with the <audio> element, a close cousin of <video>. If you have just finished the video lesson, much of this will feel familiar β€” the attributes and rules are almost the same, minus the picture.

In this lesson you will add an audio player, provide multiple formats, see why autoplay is (rightly) restricted, and control playback from JavaScript to build your own play button. The examples use a two-second chime recorded for this course.

A basic audio player

An audio player

As with video, the controls attribute tells the browser to draw its built-in player: a play button, a timeline, the current time and a volume control. Unlike video, an <audio> element without controls is completely invisible. It takes up no space and the visitor cannot see or operate it. That is useful when JavaScript controls the sound (you will do that below), but for anything the visitor is meant to listen to, always include controls.

The default player has a fixed height and a width that differs between browsers. You can set its width with CSS (width: 100% works well), but its inner look is up to the browser.

Multiple sources

Audio comes in many formats. Thankfully the situation is much simpler than it used to be:

Format MIME type Notes
MP3 audio/mpeg Plays everywhere. The safe default.
AAC (in .m4a or .mp4) audio/mp4 Widely supported; good quality at low bitrates.
Opus (in .ogg or .webm) audio/ogg, audio/webm Excellent quality and compression; supported by all current major browsers.
Vorbis (in .ogg) audio/ogg Older open format, largely replaced by Opus.
WAV audio/wav Uncompressed: perfect quality, very large files.
FLAC audio/flac Lossless compression: smaller than WAV, still large.

To offer more than one, use <source> elements. The browser plays the first one it supports, and the type attribute lets it skip the others without downloading them:

Sources and fallback

As with video, the content inside <audio> (other than <source> and <track>) is only shown by browsers that do not support the element at all. A download link is still a friendly addition, and for spoken content a written transcript on the page is even better: it helps deaf visitors, people in a noisy place, and search engines.

Autoplay, loop and muted

The same boolean attributes you met on video work on audio:

  • autoplay β€” try to start playing as soon as possible.
  • loop β€” start again from the beginning when the end is reached.
  • muted β€” start with the volume muted.
  • preload β€” none, metadata or auto, a hint about how much to download in advance.

Autoplay deserves a closer look. Browsers block autoplaying sound unless the visitor has interacted with the site first (or, in some browsers, has a history of playing media there, or has allowed it in site settings). For audio, the "muted autoplay" escape hatch that video uses makes little sense β€” silent audio is pointless.

Do not autoplay sound. Even where it is allowed, unexpected audio startles people, interferes with screen readers, and is often the first reason someone closes a tab. Accessibility guidelines require that any audio which plays automatically for more than three seconds can be paused or have its volume controlled separately. The simplest way to comply is: start sound only when the visitor asks.

Controlling audio with JavaScript

Every <audio> and <video> element is a media element with the same JavaScript interface. The methods and properties you will use most:

Member What it does
play() Starts playback. Returns a Promise.
pause() Pauses playback.
paused true if the media is paused.
currentTime The playback position in seconds; set it to seek.
duration The total length in seconds (once metadata has loaded).
volume A number from 0 (silent) to 1 (full).
muted true or false.
ended true once playback has reached the end.

And the events that tell you what is happening: play, pause, ended, timeupdate (fires repeatedly while playing), volumechange and loadedmetadata.

play() returns a Promise

Because a browser may refuse to play β€” for example, when autoplay is blocked β€” play() returns a Promise. It resolves when playback starts and rejects (usually with a NotAllowedError) when the browser says no. Always handle the rejection, so a blocked attempt does not show up as an uncaught error:

JavaScript
audio.play().catch((error) => {
  console.log('Playback was blocked:', error.name);
  // Show a "Tap to play" button instead.
});

Calling play() from inside a click handler counts as a user gesture, so it is allowed. Calling it on page load usually is not.

Building a custom play button

This example hides the default controls and drives an <audio> element from ordinary buttons. It also uses the ended event to reset the button label.

A custom sound button

A few things to notice:

  • The <audio> element has no controls, so it is invisible; the buttons are the whole interface.
  • The buttons are real <button> elements, so they work with the keyboard and screen readers out of the box. Never build a player from clickable <div>s.
  • When a sound ends, the pause event fires before ended, so the label resets automatically.

Quick sound effects. For short effects such as a notification blip, you do not even need an element in the HTML: new Audio('/sounds/blip.mp3') creates an audio element in JavaScript. Call play() on it from a click handler. For games or music apps that need precise timing and effects, look at the Web Audio API, introduced in Introduction to Web APIs.

Seeking and progress

currentTime is both readable and writable. Read it during timeupdate to show progress; set it to jump:

Progress and seeking

The <progress> element used here is covered in Output, Meter and Progress. Notice that the built-in controls and the custom buttons stay in sync automatically: they all control the same element.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. What does an audio element without the controls attribute look like?

    Without controls, an audio element is not rendered. It can still be played from JavaScript.
  2. 2. What does audio.play() return?

    play() returns a Promise. It rejects, usually with NotAllowedError, when the browser blocks playback, so you should catch it.
  3. 3. Which audio format is the safest single choice for every browser?

    MP3 plays everywhere and is reasonably small. WAV and FLAC are much larger, and MP3 needs no fallback.
  4. 4. When is calling play() most likely to succeed with sound?

    A click is a user gesture, which browsers accept as permission to play sound. Calls made without user interaction are usually blocked.

Summary

  • <audio> plays sound natively; with controls it shows a player, without it the element is invisible.
  • Offer formats with <source> and type; MP3 is the universal default, Opus in Ogg is smaller.
  • autoplay, loop, muted and preload work as on video, but autoplaying sound is usually blocked β€” and should be avoided anyway.
  • Media elements share a JavaScript API: play(), pause(), currentTime, duration, volume and events such as play, pause, ended and timeupdate.
  • play() returns a Promise; catch its rejection and call it from user gestures.
  • Provide a transcript for spoken audio.

Next up: making video and audio accessible with Captions and Subtitles.