0
0
HtmlHow-ToBeginner · 3 min read

How to Use Audio Tag in HTML: Simple Guide with Examples

Use the <audio> tag in HTML to embed sound files on a webpage. Include the src attribute for the audio file URL and add controls to show play/pause buttons. The browser will render an audio player for users to listen.
📐

Syntax

The <audio> tag is used to embed audio content. Key parts include:

  • src: URL of the audio file.
  • controls: attribute to show built-in play/pause buttons.
  • autoplay: starts playing automatically (use carefully).
  • loop: repeats audio when finished.
  • muted: starts audio muted.
html
<audio src="path/to/audio.mp3" controls></audio>
Output
An audio player with play/pause buttons appears on the webpage.
💻

Example

This example shows a simple audio player with controls for a sample audio file. Users can play, pause, and adjust volume.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Audio Tag 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 below it an audio player with play/pause and volume controls.
⚠️

Common Pitfalls

Common mistakes when using the <audio> tag include:

  • Not adding controls, so users can’t play the audio.
  • Using unsupported audio formats (use MP3 or OGG for best browser support).
  • Forgetting to include multiple <source> tags for fallback formats.
  • Autoplaying audio without user interaction, which can annoy users and be blocked by browsers.
html
<!-- Wrong: no controls, audio won't be playable -->
<audio src="sound.mp3"></audio>

<!-- Right: add controls so user can play -->
<audio src="sound.mp3" controls></audio>
📊

Quick Reference

AttributeDescription
srcURL of the audio file
controlsShow play/pause and volume controls
autoplayStart playing automatically (use carefully)
loopRepeat audio when finished
mutedStart audio muted

Key Takeaways

Always add the controls attribute so users can play and pause audio.
Use common audio formats like MP3 for best browser compatibility.
Avoid autoplay to respect user experience and browser policies.
Use multiple tags for fallback audio formats if needed.
The