How to Autoplay Audio in HTML: Simple Guide
To autoplay audio in HTML, use the
<audio> tag with the autoplay attribute. This tells the browser to start playing the audio as soon as it loads. Example: <audio src="sound.mp3" autoplay></audio>.Syntax
The <audio> tag embeds sound content in a webpage. The autoplay attribute makes the audio start playing automatically when the page loads. The src attribute specifies the audio file URL. You can also add controls to show play/pause buttons.
html
<audio src="audiofile.mp3" autoplay></audio>Output
No visible controls, audio plays automatically when page loads.
Example
This example shows an audio file that starts playing automatically without controls. The user hears the sound as soon as the page loads.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Autoplay Audio Example</title> </head> <body> <audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" autoplay></audio> </body> </html>
Output
The audio plays automatically when the page loads, no controls visible.
Common Pitfalls
Many browsers block autoplay with sound to avoid annoying users. To improve chances of autoplay working, add the muted attribute to start audio silently. Also, some browsers require user interaction before playing audio with sound.
Example of autoplay with muted audio:
html
<audio src="audiofile.mp3" autoplay muted></audio>Output
Audio plays automatically but muted (silent) to avoid browser blocking.
Quick Reference
| Attribute | Description |
|---|---|
| src | URL of the audio file |
| autoplay | Starts playing audio automatically |
| controls | Shows play/pause buttons |
| muted | Starts audio muted (silent) |
| loop | Repeats audio when finished |
Key Takeaways
Use
Browsers often block autoplay with sound; use muted attribute to avoid this.
Add controls attribute if you want users to control playback.
Always include src attribute with a valid audio file URL.
Test autoplay behavior on different browsers as policies vary.