How to Add a Background HTML Music Code

By Michael Carroll

Various methods of embedding music in a Web page have become popular since the early days of the World Wide Web. Notably, the "embed" tag in HTML, Java-based audio players and Flash-based players are all possible options for adding background music to a Web page, but no one solution has been universally embraced or is fully compatible with all browsers and platforms. The newer HTML5 standard includes the "audio" tag, which is specifically defined for embedded audio playback.

Step 1

Add the following code anywhere in the body of your HTML document to embed a music file and play it automatically when a visitor browses your website.Change the "src" attribute so that it contains the path and filename of the music file that you want to embed.

Step 2

Add the "loop" attribute if you want the music file to play over and over:

Step 3

Use multiple "source" tags instead of the "src" attribute of the "audio" tag if you want to offer the user's browser a choice of multiple file formats:In this example, the user’s browser will decide whether to play the MP3 file or the OGG file. This technique can be useful for targeting mobile devices that can only play certain audio formats.

Step 4

Nest the "embed" tag within the "audio" tag to provide support for older browsers that lack HTML5 support. Note that this use of the "embed" tag is deprecated (meaning it’s no longer officially required to be supported), so only experiment with this technique if you suspect your users will be using outdated Web browsers. Here is an example:

Tips & Warnings

  • Consider adding the "controls" attribute to the "audio" tag to allow the user to stop the music and change the volume. Additionally, consider not using the "autoplay" attribute unless there is a good reason for this browser behavior. Many users find embedded background music that unexpectedly plays without their permission annoying and will leave your website immediately.