Learn how to add background audio or music files to your website by using the HTML <audio> element and its various attributes.
To add background music/audio on your website, you can use the HTML audio element (
Let’s say you have an audio file that you want to play in the background as soon as users visit your website. Here’s the general HTML code required to do that:
<audio autoplay> <source src="your-audio-file.wav" type="audio/wav" /> </audio>
src attribute accepts both internal and external audio sources as values.
autoplay attribute. That’s required if you want the audio to start playing as soon as the user enters your webpage.
Demo: to hear an example, turn down the volume on your computer/headphones and click on this demo.
There are three supported audio formats in HTML: MP3, WAV, and OGG. In the
<audio> element you specify the format in the
|File Format||Media Type|
In this tutorial I use the WAV format, therefore I added the
type="audio/wav" attribute on the
The following is a handful of useful attributes that are built-in to the
<audio> element, and provide you fine-grained control.
To loop your background audio, you can add the
<audio autoplay loop> <source src="your-audio-file.wav" type="audio/wav" /> </audio>
To mute your background audio, you can add the
<audio muted> <source src="your-audio-file.wav" type="audio/wav" /> </audio>
Why would you use the
muted attribute? Well, you might want to disable your audio element’s audio source temporarily and switch it back on again later, without removing the entire element from your webpage.
To add controls (play, pause, etc.), use the
<audio controls> <source src="your-audio-file.wav" type="audio/wav" /> </audio>
Now the user can click play if they want to hear your audio file.
- MP3 is supported in all browsers,
- WAV is supported in all browsers except Edge/IE
- OGG is supported in all browsers except Edge/IE and Safari
As of July 2020.
Tip: add an extra
<source> to your
<audio> element as a fallback, in case that your end user uses a browser that doesn’t support your primary file format:
<audio controls> <source src="your-audio-file.wav" type="audio/wav" /> <source src="your-audio-file.mp3" type="audio/mpeg" /> </audio>
Now if the end user’s browser doesn’t support the WAV format, it will play the MP3 source instead.