The HTML5 Audio Element: A Practical Guide
Every modern browser can play sound without plugins, thanks to the <audio> element. If you understand a handful of attributes and one or two JavaScript methods, you can build almost any simple player you need.
The minimal example
<audio controls src="/media/episode-01.mp3"></audio>
The controls attribute tells the browser to draw its own play button, timeline and volume slider. Without it, the element is invisible and you have to provide your own interface.
Attributes worth knowing
- controls – shows the browser’s built-in player.
- preload –
none,metadataorauto. Usemetadataornoneon pages with several players so visitors don’t download audio they never play. - loop – restarts the track when it ends.
- muted – starts silent.
- autoplay – most browsers block autoplay with sound until the visitor interacts with the page, so don’t rely on it.
Offering more than one format
MP3 plays almost everywhere today, but you can list alternatives and let the browser pick the first one it supports:
<audio controls preload="metadata">
<source src="/media/track.opus" type="audio/ogg; codecs=opus">
<source src="/media/track.mp3" type="audio/mpeg">
Your browser does not support HTML audio.
</audio>
The text inside the element only appears in very old browsers.
Controlling playback with JavaScript
const player = document.querySelector('audio');
document.querySelector('#play').addEventListener('click', () => {
player.paused ? player.play() : player.pause();
});
Useful properties include currentTime, duration, volume (0 to 1) and playbackRate. Listen for events such as timeupdate, ended and error to update your own interface.
Accessibility tips
- Keep the native controls, or make sure custom buttons are real
<button>elements with clear labels. - Provide a transcript for spoken content.
- Never start sound automatically; let visitors choose.
Summary
For most sites, an <audio controls preload="metadata"> tag with an MP3 source is all you need. Add extra formats, custom controls or JavaScript only when your design actually requires them.
