Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to add audio to a page

Short answer

Insert <audio> with the controls attribute — the browser shows a player with a play button and volume:

<audio src="/media/t-rex-roar.mp3" controls></audio>

Without controls the element is invisible, and the sound can only be started from JavaScript.

The player width

The player can be stretched like a regular block — for example, to the full width of a card:

<figure style="margin: 0; max-width: 360px;">
  <figcaption>T. rex roar</figcaption>
  <audio src="/media/t-rex-roar.mp3" controls loop style="width: 100%;"></audio>
</figure>

loop repeats the recording. The buttons look different in each browser, and CSS barely changes them. If you need a player in the site style, it is built from buttons and JavaScript.

Formats and preloading

All modern browsers play MP3. If there are several files, list them in <source> with the type attribute. The preload="none" attribute forbids downloading the file before the button is pressed — useful when a page has many recordings.

Common mistake

autoplay is added so that music plays when the page opens. Browsers block autoplaying sound until the visitor has clicked something — and if they did not, unexpected sound would annoy people and interfere with screen readers. Leave starting to the user.

Functions used in this recipe

  • <audio> — Embeds an audio player.
  • <source> — One of the file versions for `<video>`, `<audio>` or `<picture>`.

Thanks for reading!

Donate to the site — we work hard for you.