Audio in HTML
? Audio in HTML
HTML provides the <audio> element to embed audio files directly into a webpage. It supports playback controls and multiple formats.
? Basic Syntax
<audio controls> <source src="audiofile.mp3" type="audio/mpeg"> Your browser does not support the audio element.</audio><audio>: The main tag for embedding audio.<source>: Specifies the audio file and format."controls": Adds playback controls like play/pause/volume.Fallback text: Shown if the browser doesn’t support the
<audio>tag.
? Common Audio Formats and MIME Types
| Format | MIME Type | Description |
|---|---|---|
.mp3 | audio/mpeg | Widely supported |
.ogg | audio/ogg | Open format, good quality |
.wav | audio/wav | Uncompressed, large files |
? Tip: Use multiple formats to ensure browser compatibility.
<audio controls> <source src="sound.ogg" type="audio/ogg"> <source src="sound.mp3" type="audio/mpeg"> Your browser does not support the audio element.</audio>?? HTML <audio> Attributes
| Attribute | Description | Example |
|---|---|---|
controls | Displays playback controls | <audio controls> |
autoplay | Plays audio automatically (not recommended without mute) | <audio autoplay> |
loop | Repeats the audio indefinitely | <audio loop> |
muted | Starts audio in muted state | <audio muted> |
preload | Specifies if/how the audio should be loaded | <audio preload="auto"> |
Preload options:
none: Audio is not preloaded.metadata: Only metadata (like length) is preloaded.auto: Whole audio file may be downloaded when the page loads.
? Example: Background Music (Muted & Autoplay)
<audio autoplay loop muted> <source src="bg-music.mp3" type="audio/mpeg"></audio>? Accessibility Tip
Add a title or aria-label to the audio player if it's critical to content:
<audio controls aria-label="Pronunciation of the word"> <source src="word.mp3" type="audio/mpeg"></audio>Would you like help embedding audio with custom play/pause buttons using JavaScript?