0
0
HtmlHow-ToBeginner · 3 min read

How to Add Audio in HTML: Simple Guide with Examples

To add audio in HTML, use the <audio> tag with the src attribute pointing to your audio file. You can add controls by including the controls attribute so users can play, pause, or adjust volume.
📐

Syntax

The <audio> tag embeds sound content in a web page. Use the src attribute to specify the audio file URL. Adding the controls attribute shows play/pause buttons. You can also add autoplay to start playing automatically and loop to repeat the audio.

html
<audio src="path/to/audio.mp3" controls></audio>
Output
An audio player with play/pause controls appears on the page.
💻

Example

This example shows how to add an audio player that users can control. The audio file plays only when the user clicks play.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Audio Example</title>
</head>
<body>
  <h1>Listen to this sound</h1>
  <audio src="https://www.w3schools.com/html/horse.mp3" controls></audio>
</body>
</html>
Output
A heading 'Listen to this sound' and an audio player with controls to play the horse sound appear.
⚠️

Common Pitfalls

  • Forgetting the controls attribute means no player buttons show, so users can't play the audio.
  • Using unsupported audio formats can cause the audio not to play in some browsers. Use common formats like MP3 or OGG.
  • Not providing fallback text inside the <audio> tag can confuse users if audio is not supported.
html
<!-- Wrong: No controls, no fallback -->
<audio src="sound.mp3"></audio>

<!-- Right: Controls and fallback text -->
<audio src="sound.mp3" controls>
  Your browser does not support the audio element.
</audio>
Output
The first audio tag shows no controls and no fallback text; the second shows controls and fallback text if unsupported.
📊

Quick Reference

AttributeDescription
srcURL of the audio file
controlsShows play, pause, and volume controls
autoplayStarts playing audio automatically (use carefully)
loopRepeats the audio when it ends
mutedStarts audio muted
preloadHints how much audio to load before playing (auto, metadata, none)

Key Takeaways

Use the
Include the controls attribute to let users play and pause audio easily.
Use common audio formats like MP3 for best browser support.
Add fallback text inside the
Avoid autoplay unless necessary, as it can annoy users.