HTML <audio> Tag โ Playing Sound
๐ Introduction
The <audio> tag is used to embed sound files in a webpage.
It allows users to:
- Play audio
- Listen to podcasts
- Hear voice recordings
- Control playback (play, pause, volume)
๐งฑ Basic Syntax
<audio src="audio.mp3" controls></audio>
๐ก Example
<!DOCTYPE html>
<html>
<head>
<title>Audio Example</title>
</head>
<body>
<h1>My Audio Player</h1>
<audio src="Audio.mp3" controls></audio>
</body>
</html>
๐ฅ๏ธ Output Explanation
- An audio player appears in the browser
- Users can play, pause, and adjust volume
- No audio plays automatically unless specified
๐ฏ Important Attributes
1. controls
<audio src="Audio.mp3" controls></audio>
โ Adds play/pause buttons and volume control
2. autoplay
<audio src="Audio.mp3" autoplay></audio>
โ ๏ธ Starts playing automatically (often blocked unless muted)
3. muted
<audio src="Audio.mp3" autoplay muted></audio>
โ Required for autoplay in most browsers
4. loop
<audio src="Audio.mp3" controls loop></audio>
โ Repeats audio continuously
๐ก Better Practice: Multiple Formats
Different browsers support different audio formats:
<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>
โ Improves compatibility
๐ฏ When to Use <audio>
Use it for:
- Audio players
- Podcasts
- Voice notes
- Background sounds
โ ๏ธ Important Notes
- Always include
controlsfor usability - Compress audio files for performance
- Avoid autoplay with sound (user experience issue)
๐ซ Common Mistakes
- Missing
controlsโ - Using only one format โ
- Autoplay with sound โ
- Large unoptimized audio files โ
๐จ Styling Example
<audio controls style="width:300px;">
<source src="Audio.mp3" type="audio/mpeg" />
</audio>
๐งช Mini Exercise
Create a page with:
A Audio file with controls
An audio that:
- Loops
- Is muted
A second format using
<source>