HTML Audio – Play Sound Files in Browser
The HTML <audio> element allows you to play sound files, music, or podcasts directly on a web page without any third-party plugins.
The <audio> Element
To embed audio, use the <audio> tag. Like the <video> tag, it uses the <source> tag to provide multiple file formats.
Basic Example:
<audio controls><source src="music.mp3" type="audio/mpeg">
<source src="music.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>How It Works
controls: Displays the standard browser player (Play, Pause, Volume, Seek).
</audio>: You can list multiple formats. The browser will play the first format it supports.
Fallback Text: Shown if the browser is too old to support HTML5 audio.
Autoplay and Muted Attributes
Similar to video, audio can start automatically, but browsers have strict rules:
autoplay: Starts the audio automatically (may be blocked unless the user interacts first).
muted: Plays audio without sound.
Example of Muted Autoplay:
<audio controls autoplay muted><source src="music.mp3" type="audio/mpeg">
</audio>
Supported Audio Formats
The main formats supported by HTML5 are MP3, WAV, and OGG:
| Browser | MP3 | WAV | OGG |
|---|---|---|---|
| Chrome | YES | YES | YES |
| Edge | YES | YES | YES |
| Firefox | YES | YES | YES |
| Safari | YES | YES | No |
| Opera | YES | YES | YES |
Media Types (MIME Types)
MP3: audio/mpeg
OGG: audio/ogg
WAV: audio/wav
HTML Audio Tag Reference
| Tag | Description |
|---|---|
| <audio> | Defines sound content, like music or other audio streams. |
| <source> | Defines multiple media resources for audio and video. |
Interactive Control (JavaScript)
You can control audio using JavaScript, just like video. Common methods include:
play(): Starts the audio.
pause(): Pauses the audio.
volume: Adjusts loudness (0.0 to 1.0).