anonymous_coder
anonymous_coder

Reputation: 139

playing an audio automatically after a button is selected

i have 4 buttons in my html. i am selecting a button randomly and want to play a sound for selected button.

this is my index.js

buttonColours=["red", "blue", "green", "yellow"];
gamePattern=[];
function nextSequence(){
  var r = Math.floor(Math.random()*4);
  gamePattern.push(buttonColours[r]);
  var b = gamePattern[0];
$("#"+b).fadeOut(100).fadeIn(100);
var a = new Audio("sounds\\"+b+".mp3");
a.play();
}
nextSequence();

i am getting this error on the console.

index.js:12 Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first

Upvotes: 2

Views: 1497

Answers (1)

Apollo24
Apollo24

Reputation: 95

Most Browsers won't allow you to autoplay music without an action from the user himself. You can use a button to call your function. It could look something like this:

<button id="start">Start</button>
var start = document.getElementById("start");

start.onclick = function() {
  var r = Math.floor(Math.random()*4);
  gamePattern.push(buttonColours[r]);
  var b = gamePattern[0];
$("#"+b).fadeOut(100).fadeIn(100);
var a = new Audio("sounds\\"+b+".mp3");
a.play();
}

Upvotes: 2

Related Questions