AI Workshop: learn to build apps with AI →
HTML Media: How to Embed Audio in HTML

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


The audio tag allows you to embed audio content in your HTML pages.

Basic Usage

You can play an audio file by referencing it with the src attribute:

<audio src="file.mp3"></audio>

By default, the browser does not show any controls. To display the built-in controls, add the controls attribute:

<audio src="file.mp3" controls></audio>

Common Attributes

autoplay

Play the audio automatically when the page loads:

<audio src="file.mp3" controls autoplay></audio>

Note: Mobile browsers typically don’t allow autoplay.

loop

Restart the audio when it reaches the end:

<audio src="file.mp3" controls loop></audio>

muted

Start with the audio muted:

<audio src="file.mp3" controls muted></audio>

type

Specify the MIME type of the audio file:

<audio src="file.mp3" controls type="audio/mpeg"></audio>

preload

Control how the browser preloads the audio:

<audio src="file.mp3" preload="auto"></audio>

Values: none, metadata (default), or auto.

Multiple Sources

To support different audio formats and older browsers, use the source element:

<audio controls>
  <source src="song.opus" type="audio/ogg; codecs=opus">
  <source src="song.ogg" type="audio/ogg; codecs=vorbis">
  <source src="song.mp3" type="audio/mpeg">
</audio>

The browser will use the first format it supports.

Fallback Content

Add text between the opening and closing tags for browsers that don’t support the audio element:

<audio src="song.mp3" controls>
  Your browser does not support the audio element.
</audio>

JavaScript Events

You can listen for various events on audio elements:

const audio = document.querySelector('audio')

audio.addEventListener('play', () => {
  console.log('Audio started playing')
})

audio.addEventListener('pause', () => {
  console.log('Audio paused')
})

audio.addEventListener('ended', () => {
  console.log('Audio finished')
})

Common events include: play, pause, ended, timeupdate, and volumechange.

Lessons in this unit:

0: Introduction
1: How to Add Images in HTML
2: How to Create Responsive Images with srcset and picture
3: ▶︎ How to Embed Audio in HTML
4: How to Embed Video in HTML
5: How to Embed External Content with iframe
6: An in-depth SVG tutorial
7: The WebP Image Format