1

When the page loads I want an audio file to play automatically. It worked once, but when I refreshed I got the "play() failed because the user didn't interact with the document first" error. When I changed some code it worked once again but after refreshing I kept getting the error.

I've tried simulating a click which, as I said above, worked once.

This is the code I have right now:

$(".header-bg").click();
console.log("clicked");

$(document).ready(function() {
    console.log("loaded");
    $('#medieval-music')[0].play();
});

The two console logs get logged but the music doesn't play.

  • 3
    Most browsers have autoplay blocking capabilities - [see here for some more info](https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide). Making audio play automatically is fundamentally anti-user - many people find it annoying, it consumes extra bandwidth, and it might suddenly play an unexpected noise at an inappropriate moment. Please don't attempt to inflict this on your users, they will not thank you for it. Allow them to play the audio if they choose to, instead. In any case, due to the aforementioned blocking capabilities, you have no way to guarantee it will always work. – ADyson Nov 11 '19 at 10:01
  • I understand that, but - It's for a game for a school project, that's why I do want the music to play. – fronky bonk Nov 11 '19 at 10:04
  • Ok, but the browser doesn't know or care about the circumstances. To be honest I don't see why that's a problem? Just let the music play once the user agrees to commence the game. – ADyson Nov 11 '19 at 10:06
  • more info on autoblock: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes – yqlim Nov 11 '19 at 10:38

2 Answers2

1

I'm assuming you are using an html5 <audio> tag. If so, put it as mute by default like this:

<audio mute="true"></audio>

The problem is that most of the browsers nowadays block the autoplay capability to prevent noise to the users when they open new tabs.

For more subject about this answer, please check out this.

Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
-2

Using autoplay attributes in html <audio controls autoplay></audio> every time you load your page the audio file will automatically play

  • 1
    No, not necessarily. The browser can block it. That's the whole reason for the question. Read https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide – ADyson Nov 11 '19 at 10:06
  • more info on autoblock: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes – yqlim Nov 11 '19 at 10:38