How to play MP3 in the background music automatically?

How to Play an MP3 in the Background Automatically [Solved]

If you’re building a web page and have ever wondered how to automatically play music, this article is for you.

However, while there are a few legitimate reasons to auto-play audio when someone visits a page, at the time of writing, it’s widely considered a bad UX (user experience) practice. Doubly so if there isn’t any sort of user interaction like a click or button press first, or you purposefully hide the player controls.

But maybe you’re building a game and want audio to play automatically when the page loads. Whatever the reason, read on to see some possible solutions.

Simple implementation

First, add an audio element to the page and load the audio’s source with the src attribute:

<audio src="https://www.bensound.com/bensound-music/bensound-moose.mp3"></audio>

Next, use JavaScript to listen to the DOMContentLoaded event, select the audio event and call audio.play():

window.addEventListener("DOMContentLoaded", event => {
  const audio = document.querySelector("audio");
  audio.volume = 0.2;
  audio.play();
});

Again, this is widely considered a bad UX experience, and was blocked in Chrome until recent updates. Because this method takes control out of your users’ hands, it may still be blocked in Firefox.

Also, while there is an autoplay attribute for the audio element, it’s not recommended, and might be blocked in all major browsers depending on how it’s used.

A better implementation

The easiest way to improve UX and reduce the chances of annoying visitors to your site is to only play audio after the user interacts with the page.

For example, you could add a simple mute/unmute that starts in the muted state, and only plays music when it’s clicked:


Here’s what the code might look like for that:

const button = document.querySelector("#button");
const icon = document.querySelector("#button > i");
const audio = document.querySelector("audio");

button.addEventListener("click", () => {
  if (audio.paused) {
    audio.volume = 0.2;
    audio.play();
    icon.classList.remove('fa-volume-up');
    icon.classList.add('fa-volume-mute');
    
  } else {
    audio.pause();
    icon.classList.remove('fa-volume-mute');
    icon.classList.add('fa-volume-up');
  }
  button.classList.add("fade");
});

The most important parts are the audio.play() and audio.pause() methods. Initially the music is paused or muted, which is the default behavior for the audio element. Then as soon as it’s clicked, the audio starts playing.

Check out this live example of a page with the mute/unmute button.

In summary

There are a few good reasons to create a page that auto-plays music when it loads, but it’s still widely considered bad practice. If you need to play audio, it’s recommended that you have controls, even if it’s just a simple mute/unmute button.

Or you could get creative – if you’re building a game, how about adding a start screen when users have to click a button to start playing? Then it’s clear that your page might have some sort of audio, whether it’s music or sound effects.

Whatever route you choose, remember to keep user experience in mind as you go. Stay safe and happy coding.

Note: Big thanks to lasjorg for sharing the code and creating the example page used in this article. You can find the original in the comments below.

Auto-playing audio without user interaction and removing the controls is consider pretty poor UX. Is there a reason why you can’t have the player visible?

It is webpage to the video game app… and I want the music to play in the background… so it looks like your in a game… but I guess i can find some way to start it with a JS click.

What does your code look like for your audio player? You can always look into the autoplay property of the DOM. You would listen to when the DOM has loaded, and if it has, set the autoplay of your mp3 to true. You can check more about that here https://www.w3schools.com/jsref/prop_audio_autoplay.asp

Or you can have something like this in your HTML

<audio controls autoplay>
  <source src="music.mp3" type="audio/mpeg">
</audio>
1 Like

Yes, I have this code, but the music does not play automatically. you have push play to make it work.

All browsers disable autoplay on page onload in 2018.

I just mocked something up, and the audio is autoplaying on my end using the autoplay flag for the audio controls.

I’m using the latest version of Chrome as well.

Ok, so after a little bit of researching, the autoplay feature for audio would work on some browsers and not all. So you may have to create an iframe and the audio one as well, and using javascript to toggle each one depending which browser they are using.

Check out the solution on this stack overflow thread on how that can be done, this seems to be the only way from what I gathered. https://stackoverflow.com/questions/50490304/how-to-make-audio-autoplay-on-chrome

I would suggest making a mute/unmute button, you can remove it or move and fade it out after the user clicks it.

https://codepen.io/lasjorg/full/GRKreyJ

UX can be difficult when working on your own stuff because you become attached to the project differently then if you are just a user. Personally, as a user, I think that auto-playing sound is fairly obnoxious and in my opinion often a bad design choice.

1 Like

What about using jQuery/JavaScript to start playing the audio when the document is ready?
From jQuery document ready page:

$( document ).ready(function() {
    //Do something
});

Or the shorthand version:

$(function() {
    //Do something
});

That //Do something could be

let sound = document.getElementById("audioId");
sound.currentTime = 0;
sound.loop = true; //if you want it to restart playing automatically when it ends
sound.play();
1 Like

I believe HTMLMediaElement.play() has to be called as part of user interaction or it might get blocked by the browser.

This (seems to) work in Chrome but it is blocked in Firefox.

Block console messages:

Autoplay is only allowed when approved by the user, the site is activated by the user, or media is muted.

NotAllowedError: The play method is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

Yes, I tried this. It didn’t work. I kept getting error with slient.mp3 iframe …

yes i agree about the music playing on open of the page…

I will have to try this out… but I haven’t learned JQ yet… only JS. thanks.

It is very little code, the second link I posted does that. But as said it is blocked in Firefox (maybe other browsers as well).

jQuery is JS, it doesn’t do anything special, browsers will still attempt to block you from making some aggressively anti-user decisions.

Thanks for letting me to know. I really didn’t know this was an issue till now.
I guess there is just no easy way…

Yeah, I would urge you to allow the user to make the decision to start up the media playing themselves. What you’re asking is a common request, and there are ways to do it – see how many news media orgs have managed to circumvent the restriction and have autoplaying video (which is kinda funny when you consider that the reason they aggressively push video journalism is due to a Facebook bug/misunderstanding of analytics, but anyway) – but it is always going to involve hacks to work around browser restrictions

what ways are there to do it? I tried the iframe/audio and a few other hacks, but none worked for me.

Maybe you could put a small box in a corner with the play/pause functionality.
When the user loads the page, he gets a pop up saying that he/she should press play to have a richer game experience.

Try these codes… it autoplay immediately or after a reload page at my web site ADS-B and VHF audio sharing feeder @ http://rodyeo.dyndns.org hosting on Raspberry Pi 3B+

<audio width="150px" height="25" allow=”autoplay” autoplay="autoplay" src="http://rodyeo.dyndns.org:8000/wmsa" controls="controls">If stream does not start automatically press the play button</audio >