learn2kode.in

HTML Audio Element

The <audio> element in HTML is used to embed sound files such as music, voice recordings, or sound effects into a webpage. It supports common formats like MP3, WAV, and OGG.

Syntax

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

Common Audio Formats

Format Description
MP3 Most widely supported format
WAV High-quality uncompressed
OGG Open-source compressed

Why Use Multiple Tags?

Different browsers support different audio formats. Using <source> ensures compatibility:

<audio controls>
  <source src="sound.mp3" type="audio/mpeg">
  <source src="sound.ogg" type="audio/ogg">
  Your browser does not support the audio element.
</audio>

Common Attributes of the <audio> Tag

Attribute Description
controls Displays play/pause, seek bar, and volume controls
autoplay Starts playing automatically
loop Repeats the audio continuously
muted Starts audio with the sound turned off
preload Controls how the audio loads (auto, metadata, none)

Preload Attribute Options

Value Meaning
auto Browser decides; often loads entire file
metadata Only loads basic info (duration, size)
none Does not load the file until the user plays it

Example with All Attributes

<audio 
  src="music.mp3" 
  controls 
  autoplay 
  loop 
  muted 
  preload="metadata">
</audio>

Example with Download Fallback Text

<audio controls>
  <source src="song.mp3" type="audio/mpeg">
  <source src="song.ogg" type="audio/ogg">
  Your browser does not support the audio element. 
  <a href="song.mp3">Download the audio</a>
</audio>