W3docs

HTML <audio> Tag

The HTML <audio> tag defines a sound, such as music or other audio streams. Learn how to use <audio> tag with syntax and examples with W3docs tutorial.

The <audio> tag is one of the HTML5 elements added to allow embedding audio files into a web page. Since not all browsers support all audio formats, the audio file is encoded using special codecs.

The <source> tag or the src attribute is used to indicate the variations of the same audio file. The path to an audio file can contain absolute or relative URLs.

Syntax

The <audio> tag comes in pairs. The content is written between the opening (<audio>) and closing (</audio>) tags.

HTML <audio> Tag

<audio>
  <source src="URL">
  <source src="URL">
</audio>

Example of the HTML <audio> tag:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <audio controls>
      <source src="/build/audios/jingle_bells.ogg" type="audio/ogg" />
      <source src="/build/audios/audio.mp3" type="audio/mpeg" />
    </audio>
    <p>Click the play button</p>
  </body>
</html>

The Loop Attribute

Using the loop attribute will make the audio file play over and over again:

HTML <audio> Tag

<audio src="audio.mp3" autoplay loop></audio>

Displaying Browser Controls

You can let the browser display controls to the user, such as volume or play/pause. It is done with the help of the controls attribute.

Displaying Browser Controls code

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

Example of the HTML <audio> tag with the controls attribute:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <audio controls src="/build/audios/audio.mp3">
      Your browser does not support the audio element.
    </audio>
    <p>Click the play button</p>
  </body>
</html>

Several File Formats

With the <audio> tag you can define multiple formats of the same audio file.

Several File Formats example

<audio controls>
  <source src="audio.ogg">
  <source src="audio.mp3">
</audio>

Attributes

The <audio> tag has attributes that indicate the path to the audio file, playback behavior, etc. The controls, autoplay, loop, and muted attributes are boolean; their values can be omitted. If specified, the corresponding function is enabled by default.

AttributeValueDefinition
autoplayPlays the audio file automatically after loading the page.
controlsDisplays the control panel (play/pause, volume, etc.). If the controls attribute is missing, the audio will not be visible on the page.
loopRepeats the audio file continuously from the beginning after it finishes.
mutedMutes the audio by default.
preloadauto, metadata, noneDefines the preloading strategy for the audio file.
srcURLSpecifies the path to the audio file.

The <audio> tag supports the Global Attributes and the Event Attributes.

Practice

Practice

What are the properties of the HTML audio tag?