Marmik Patel
Marmik Patel

Reputation: 192

play sound on first time html page load

I am trying to play audio on page load but i am getting error Uncaught (in promise) DOMException

$(document).ready(function() {

        var sound = new Audio("audio.mp3"); 
        sound.play();  

});

Upvotes: 0

Views: 6920

Answers (3)

Marmik Patel
Marmik Patel

Reputation: 192

I found the way it works finally.

To enable sound on first time when page load run below link on google chrome

  chrome://flags/#autoplay-policy

then choose option "No user gesture is required".

and last click on "relaunch now" button for restart google chrome

Upvotes: 0

Sreeraj_ms
Sreeraj_ms

Reputation: 551

Please try like this

HTML

<audio id="my_audio" src="bg.mp3" loop="loop"></audio>

JQuery

$(document).ready(function() {
   setTimeOut(function(){$("#my_audio").get(0).play();},1000)
});

var promise = document.querySelector('my_audio').play();

if (promise !== undefined) {
  promise.then(_ => {
    // Autoplay started!
  }).catch(error => {
    // Autoplay was prevented.
    // Show a "Play" button so that user can start playback.
$("#my_audio").get(0).play()
  });
}

please make sure that audio file is in same path.

Upvotes: 1

Muhammad Shahjad
Muhammad Shahjad

Reputation: 112

Here is my sample code. If you can use cookies it will be better

<audio id="my_audio" src="audio.mp3" loop="loop"></audio>
and add a script like this:

window.onload = function () {
    if (localStorage.getItem("hasCodeRunBefore") === null) {
         document.getElementById("my_audio").play();
        localStorage.setItem("hasCodeRunBefore", true);
    }
}

Upvotes: 1

Related Questions