HTML Audio
The
Audio playback patterns
EXAMPLE
<!-- Simplest case: browser-provided controls -->
<audio controls src='/track.mp3'></audio>
<!-- Multiple formats for maximum compatibility -->
<audio controls preload='metadata'>
<source src='/track.opus' type='audio/ogg; codecs=opus' />
<source src='/track.aac' type='audio/aac' />
<source src='/track.mp3' type='audio/mpeg' />
Your browser does not support audio.
</audio>
<!-- Background sound effect (no controls, autoplay - use sparingly) -->
<audio src='/whoosh.mp3' preload='auto' id='sfx'></audio>
<button onclick='document.getElementById("sfx").play()'>Play SFX</button>
<!-- Programmatic control + UI -->
<audio id='podcast' src='/episode-01.mp3' preload='metadata'></audio>
<div>
<button id='play'>Play</button>
<button id='pause'>Pause</button>
<input id='seek' type='range' min='0' max='100' value='0' />
<input id='vol' type='range' min='0' max='1' step='0.05' value='1' />
<span id='time'>0:00 / 0:00</span>
</div>
<script>
const a = document.getElementById('podcast');
const seek = document.getElementById('seek');
const time = document.getElementById('time');
document.getElementById('play').onclick = () => a.play();
document.getElementById('pause').onclick = () => a.pause();
document.getElementById('vol').oninput = (e) => a.volume = e.target.value;
seek.oninput = (e) => a.currentTime = (e.target.value / 100) * a.duration;
const fmt = (s) => {
const m = Math.floor(s / 60); const ss = String(Math.floor(s % 60)).padStart(2, '0');
return \`${m}:${ss}\`;
};
a.addEventListener('timeupdate', () => {
seek.value = (a.currentTime / a.duration) * 100;
time.textContent = \`${fmt(a.currentTime)} / ${fmt(a.duration)}\`;
});
</script>
Why it matters
Browsers block autoplay with sound by default - you can only play after a user gesture. Plan your UI around that. For background music or short SFX in apps, the Web Audio API gives you fine-grained control beyond what
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Audio</title>
</head>
<body>
<h1>HTML Audio</h1>
<p>This is a demo page for the "HTML Audio" lesson.</p>
</body>
</html>
Try it Yourself »
Exercise
Provide a fallback MP3 track when the browser does not support OGG.
<audio controls>
<source src="song.ogg" type="audio/ogg">
<
src="song.mp3" type="audio/mpeg">
</audio>
Six letters; same tag as the OGG line.
Discussion
Loading…