HTML <audio> Tag

The HTML <audio> tag is used to embed audio files in a web page, allowing users to play sounds, music, or voice recordings directly in their browser. It supports multiple formats and can include built-in playback controls.

Basic Syntax

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

Explanation:

<audio> Defines the audio player.

<source> - Specifies the audio file with different formats for compatibility.

Fallback Text - Displays if the browser does not support the <audio> tag.

Common <audio> Attributes

src - Defines the audio file location (alternative to <source>).

<audio src="audio.mp3">

controls - Displays built-in audio controls (play, pause, volume).

<audio controls>

autoplay - Starts playing the audio automatically.

<audio autoplay>

loop - Repeats the audio indefinitely.

<audio loop>

muted - Starts the audio with sound muted.

<audio muted>

preload - Defines how the audio is loaded before playback (auto, metadata, none).

<audio preload="metadata">

Adding Multiple Audio Formats

Different browsers support different audio formats. Providing multiple sources ensures wider compatibility.

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

Common Audio Formats:

MP3 (audio/mpeg) - Most widely supported.

Ogg (audio/ogg) - Open-source format.

WAV (audio/wav) - High quality but large file size.

Example: Full Audio Implementation

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

Summary

<audio> - Defines an audio player.

<source> - Provides multiple audio formats for compatibility.