Media Element
HTML5
The audio element embeds sound content into documents. It supports multiple audio formats, provides built-in playback controls, and includes a powerful JavaScript API for custom audio players and interactive experiences.
Interactive code playground requires JavaScript. Here's the code:
<audio controls>
<source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
type="audio/mpeg">
Your browser doesn't support audio playback.
</audio>
< audio src = " audio.mp3 " controls ></ audio >
<!-- With multiple sources -->
< source src = " audio.opus " type = " audio/opus " >
< source src = " audio.mp3 " type = " audio/mpeg " >
Your browser doesn't support audio.
Displays the browser’s default audio controls (play, pause, volume, progress):
Interactive code playground requires JavaScript. Here's the code:
<!-- With controls -->
<audio controls src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3">
Your browser doesn't support audio.
</audio>
<!-- Without controls (controlled via JavaScript) -->
<audio id="hidden-audio"
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3"></audio>
<button onclick="document.getElementById('hidden-audio').play()">Play</button>
<button onclick="document.getElementById('hidden-audio').pause()">Pause</button>
Specifies the audio file URL:
Interactive code playground requires JavaScript. Here's the code:
<audio controls
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3">
Fallback text for unsupported browsers.
</audio>
Starts playing automatically when the page loads:
Interactive code playground requires JavaScript. Here's the code:
<!-- Autoplay with muted (most browsers allow this) -->
<audio controls autoplay muted
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3">
</audio>
<p>Note: Most browsers block autoplay unless muted</p>
Repeats the audio when it reaches the end:
Interactive code playground requires JavaScript. Here's the code:
<audio controls loop
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-6.mp3">
Your browser doesn't support audio.
</audio>
<p>This audio will loop indefinitely</p>
Starts with audio muted:
Interactive code playground requires JavaScript. Here's the code:
<audio controls muted
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-7.mp3">
Audio not supported.
</audio>
<p>Audio starts muted; use controls to unmute</p>
Controls how much audio to download on page load:
<!-- Don't preload: save bandwidth -->
< audio controls preload = " none "
<!-- Load only metadata (duration, dimensions) -->
< audio controls preload = " metadata "
<!-- Load entire file (default if controls present) -->
< audio controls preload = " auto "
Attribute Description Values Default srcAudio file URL URL - controlsShow playback controls Boolean falseautoplayAuto-start playback Boolean falseloopRepeat playback Boolean falsemutedStart muted Boolean falsepreloadPreload strategy none, metadata, autometadatacrossoriginCORS settings anonymous, use-credentials-
Format MIME Type Chrome Firefox Safari Edge MP3 audio/mpeg✓ ✓ ✓ ✓ AAC audio/mp4✓ ✓ ✓ ✓ Opus audio/opus✓ ✓ ✓ ✓ Ogg Vorbis audio/ogg✓ ✓ ✗ ✓ WAV audio/wav✓ ✓ ✓ ✓ FLAC audio/flac✓ ✓ ✓ ✓
Interactive code playground requires JavaScript. Here's the code:
<audio controls>
<!-- Best compression: Opus -->
<source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3"
type="audio/opus">
<!-- Good compression: AAC -->
<source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3"
type="audio/mp4">
<!-- Universal: MP3 -->
<source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3"
type="audio/mpeg">
Your browser doesn't support HTML5 audio.
<a href="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3">Download audio</a>
</audio>
Provide text transcripts for audio content:
Interactive code playground requires JavaScript. Here's the code:
<figure>
<figcaption>
<strong>Podcast Episode 1: Introduction</strong>
</figcaption>
<audio controls
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-9.mp3">
Your browser doesn't support audio playback.
</audio>
<details>
<summary>Show Transcript</summary>
<p>
[Transcript would go here]<br>
Welcome to our podcast. Today we'll be discussing...
</p>
</details>
</figure>
Interactive code playground requires JavaScript. Here's the code:
<div>
<label for="audio-1">Background Music</label>
<audio id="audio-1" controls
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-10.mp3">
Audio not supported.
</audio>
</div>
<div>
<p id="audio-desc">Nature sounds: rain and thunder</p>
<audio controls aria-labelledby="audio-desc"
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-11.mp3">
Audio not supported.
</audio>
</div>
Interactive code playground requires JavaScript. Here's the code:
<audio controls
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-12.mp3">
Your browser doesn't support audio.
<a href="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-12.mp3"
download>Download audio file</a>
</audio>
<p>
<a href="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-12.mp3"
download>Download MP3</a>
</p>
Interactive code playground requires JavaScript. Here's the code:
<audio id="player"
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3">
</audio>
<div>
<button onclick="play()">▶ Play</button>
<button onclick="pause()">⏸ Pause</button>
<button onclick="stop()">⏹ Stop</button>
<button onclick="rewind()">⏪ Rewind 10s</button>
</div>
<div id="status">Ready</div>
<script>
const audio = document.getElementById('player');
const status = document.getElementById('status');
function play() {
audio.play();
status.textContent = 'Playing...';
}
function pause() {
audio.pause();
status.textContent = 'Paused';
}
function stop() {
audio.pause();
audio.currentTime = 0;
status.textContent = 'Stopped';
}
function rewind() {
audio.currentTime = Math.max(0, audio.currentTime - 10);
}
</script>
Interactive code playground requires JavaScript. Here's the code:
<audio id="vol-audio" controls
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3">
</audio>
<div>
<label for="volume">Volume:</label>
<input type="range" id="volume" min="0" max="100" value="50">
<span id="vol-display">50%</span>
</div>
<script>
const audio = document.getElementById('vol-audio');
const volumeSlider = document.getElementById('volume');
const volDisplay = document.getElementById('vol-display');
volumeSlider.addEventListener('input', (e) => {
const volume = e.target.value / 100;
audio.volume = volume;
volDisplay.textContent = e.target.value + '%';
});
// Initialize
audio.volume = 0.5;
</script>
Interactive code playground requires JavaScript. Here's the code:
<audio id="track-audio" controls
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3">
</audio>
<div>
<progress id="progress" max="100" value="0"></progress>
<div id="time">0:00 / 0:00</div>
</div>
<script>
const audio = document.getElementById('track-audio');
const progress = document.getElementById('progress');
const timeDisplay = document.getElementById('time');
audio.addEventListener('timeupdate', () => {
const percent = (audio.currentTime / audio.duration) * 100;
progress.value = percent;
const current = formatTime(audio.currentTime);
const total = formatTime(audio.duration);
timeDisplay.textContent = current + ' / ' + total;
});
function formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return mins + ':' + (secs < 10 ? '0' : '') + secs;
}
</script>
Interactive code playground requires JavaScript. Here's the code:
<audio id="event-audio" controls
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3">
</audio>
<ul id="events" style="max-height: 100px; overflow-y: auto;"></ul>
<script>
const audio = document.getElementById('event-audio');
const eventsList = document.getElementById('events');
const events = ['play', 'pause', 'ended', 'loadstart', 'loadeddata', 'canplay', 'playing'];
events.forEach(eventName => {
audio.addEventListener(eventName, () => {
const li = document.createElement('li');
li.textContent = eventName + ' - ' + new Date().toLocaleTimeString();
eventsList.insertBefore(li, eventsList.firstChild);
});
});
</script>
Event Description When Fired playPlayback started User clicks play or .play() called pausePlayback paused User clicks pause or .pause() called endedPlayback finished Audio reaches the end timeupdateCurrent time changed During playback (4-60 times per second) volumechangeVolume changed User or script changes volume loadstartLoading started Browser starts loading loadeddataFirst frame loaded Enough data to start playing canplayCan start playing Enough data buffered canplaythroughCan play without buffering Entire file can play without stopping errorError occurred Loading or playback error
Interactive code playground requires JavaScript. Here's the code:
<style>
.player {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1.5rem;
border-radius: 12px;
color: white;
max-width: 400px;
}
.player-controls {
display: flex;
align-items: center;
gap: 1rem;
margin-top: 1rem;
}
.player button {
background: white;
border: none;
width: 40px;
height: 40px;
border-radius: 50%;
cursor: pointer;
font-size: 16px;
}
.player-progress {
flex: 1;
height: 6px;
background: rgba(255,255,255,0.3);
border-radius: 3px;
cursor: pointer;
position: relative;
}
.player-progress-fill {
height: 100%;
background: white;
border-radius: 3px;
width: 0%;
transition: width 0.1s;
}
</style>
<div class="player">
<div><strong>Now Playing</strong></div>
<div>Audio Track</div>
<div class="player-controls">
<button onclick="customPlayer.toggle()">▶</button>
<div class="player-progress" onclick="customPlayer.seek(event)">
<div class="player-progress-fill" id="custom-fill"></div>
</div>
<span id="custom-time">0:00</span>
</div>
</div>
<audio id="custom-audio"
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3">
</audio>
<script>
const customPlayer = {
audio: document.getElementById('custom-audio'),
fill: document.getElementById('custom-fill'),
time: document.getElementById('custom-time'),
button: document.querySelector('.player button'),
toggle() {
if (this.audio.paused) {
this.audio.play();
this.button.textContent = '⏸';
} else {
this.audio.pause();
this.button.textContent = '▶';
}
},
seek(e) {
const rect = e.currentTarget.getBoundingClientRect();
const percent = (e.clientX - rect.left) / rect.width;
this.audio.currentTime = percent * this.audio.duration;
}
};
customPlayer.audio.addEventListener('timeupdate', () => {
const percent = (customPlayer.audio.currentTime / customPlayer.audio.duration) * 100;
customPlayer.fill.style.width = percent + '%';
const mins = Math.floor(customPlayer.audio.currentTime / 60);
const secs = Math.floor(customPlayer.audio.currentTime % 60);
customPlayer.time.textContent = mins + ':' + (secs < 10 ? '0' : '') + secs;
});
</script>
Interactive code playground requires JavaScript. Here's the code:
<audio id="speed-audio" controls
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-6.mp3">
</audio>
<div>
<label for="speed">Playback Speed:</label>
<select id="speed">
<option value="0.5">0.5x</option>
<option value="0.75">0.75x</option>
<option value="1" selected>1x (Normal)</option>
<option value="1.25">1.25x</option>
<option value="1.5">1.5x</option>
<option value="2">2x</option>
</select>
</div>
<script>
const audio = document.getElementById('speed-audio');
const speedSelect = document.getElementById('speed');
speedSelect.addEventListener('change', (e) => {
audio.playbackRate = parseFloat(e.target.value);
});
</script>
Interactive code playground requires JavaScript. Here's the code:
<audio id="playlist-audio" controls></audio>
<div>
<button onclick="playlist.play(0)">Track 1</button>
<button onclick="playlist.play(1)">Track 2</button>
<button onclick="playlist.play(2)">Track 3</button>
</div>
<div>Current: <span id="current-track">None</span></div>
<script>
const playlist = {
audio: document.getElementById('playlist-audio'),
tracks: [
'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3',
'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3'
],
play(index) {
this.audio.src = this.tracks[index];
this.audio.play();
document.getElementById('current-track').textContent = 'Track ' + (index + 1);
}
};
// Auto-play next track
playlist.audio.addEventListener('ended', () => {
const currentIndex = playlist.tracks.indexOf(playlist.audio.src);
if (currentIndex < playlist.tracks.length - 1) {
playlist.play(currentIndex + 1);
}
});
</script>
Interactive code playground requires JavaScript. Here's the code:
<audio id="viz-audio" controls crossorigin="anonymous"
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-7.mp3">
</audio>
<canvas id="visualizer" width="400" height="100"
style="width: 100%; background: #000; display: block;"></canvas>
<script>
const audio = document.getElementById('viz-audio');
const canvas = document.getElementById('visualizer');
const ctx = canvas.getContext('2d');
// Note: Web Audio API visualization requires same-origin or CORS
// This is a simplified visual representation
let animationId;
audio.addEventListener('play', () => {
visualize();
});
audio.addEventListener('pause', () => {
cancelAnimationFrame(animationId);
});
function visualize() {
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Simple bar visualization (simulated)
ctx.fillStyle = '#667eea';
for (let i = 0; i < 50; i++) {
const height = Math.random() * canvas.height;
const x = (canvas.width / 50) * i;
ctx.fillRect(x, canvas.height - height, 6, height);
}
animationId = requestAnimationFrame(visualize);
}
</script>
Interactive code playground requires JavaScript. Here's the code:
<audio id="bgm" loop muted
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3">
</audio>
<button id="bgm-toggle">🔇 Enable Background Music</button>
<script>
const bgm = document.getElementById('bgm');
const toggle = document.getElementById('bgm-toggle');
toggle.addEventListener('click', () => {
if (bgm.paused) {
bgm.play();
bgm.muted = false;
toggle.textContent = '🔊 Disable Background Music';
} else {
bgm.pause();
toggle.textContent = '🔇 Enable Background Music';
}
});
</script>
Interactive code playground requires JavaScript. Here's the code:
<article style="border: 1px solid #ccc; padding: 1rem; border-radius: 8px;">
<h3 style="margin-top: 0;">Episode 42: Web Audio</h3>
<p style="color: #666; font-size: 0.9rem;">
Duration: 45:30 • Published: Dec 11, 2024
</p>
<audio controls style="width: 100%;"
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-9.mp3">
Your browser doesn't support audio playback.
</audio>
<details style="margin-top: 1rem;">
<summary>Episode Notes</summary>
<p>In this episode, we explore the Web Audio API...</p>
</details>
</article>
Interactive code playground requires JavaScript. Here's the code:
<audio id="click-sound" preload="auto"
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-10.mp3">
</audio>
<button onclick="playSound()">🔔 Play Sound Effect</button>
<script>
function playSound() {
const sound = document.getElementById('click-sound');
sound.currentTime = 0; // Reset to start
sound.play();
}
</script>
Use appropriate preload values
none for audio users may not play
metadata for typical use cases (default)
auto for audio likely to be played
Compress audio files
Use tools like Audacity or FFmpeg
Target bitrates: 128kbps for music, 64kbps for voice
Choose the right format
MP3: Universal compatibility
Opus: Best quality/size ratio for modern browsers
AAC: Good alternative to MP3
Lazy load when possible
Don’t load audio until needed
Use JavaScript to set src on user interaction
Feature Chrome Firefox Safari Edge Basic <audio> 3+ 3.5+ 4+ 12+ controls attribute3+ 3.5+ 4+ 12+ autoplay attribute3+ 3.5+ 4+ 12+ loop attribute3+ 3.5+ 4+ 12+ preload attribute3+ 4+ 4+ 12+ JavaScript API 3+ 3.5+ 4+ 12+