2

In the code, I am generating random color from the array and I want to produce sound related to it.

Here is the javascript code

var gamePattern = [];
var buttonColours = ["red", "blue", "green", "yellow"];
var randomChosenColour = buttonColours[nextSequence()];
gamePattern.push(randomChosenColour);


function nextSequence() {
  return Math.floor(Math.random() * 4);
}



$("." + randomChosenColour).fadeOut(100).fadeIn(100);

$("." + randomChosenColour).ready(function(){
  var audio = new Audio("sounds/"+ randomChosenColour +".mp3");
  audio.play();
});

here is the html code

<div class="container">
    <div lass="row">

      <div type="button" id="green" class="btn green" >
        <!-- <audio id="sound" src="sounds/green.mp3"></audio> -->
      </div>

      <div type="button" id="red" class="btn red" >
        <!-- <audio id="sound" src="sounds/green.mp3"></audio> -->
      </div>
    </div>

    <div class="row">

      <div type="button" id="yellow" class="btn yellow" >
        <!-- <audio id="sound" src="sounds/green.mp3"></audio> -->
      </div>
      <div type="button" id="blue" class="btn blue" >
        <!-- <audio id="sound" src="sounds/green.mp3"></audio> -->
      </div>

    </div>

  </div>

I tried many ways to produce sounds but I am getting errors in the console.

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

Any help here would be appreciated.

  • 1
    There's nothing wrong with your code. The error you're seeing is due to a restriction in modern browsers which prevents websites auto-playing annoying music/sounds when you visit a site. Sound can only be played when a user has 'interacted' with the site, for example, when they have clicked a button, or typed in to a form control. The Google update regarding this restriction is here: https://developer.chrome.com/blog/autoplay/. – Rory McCrossan Aug 27 '22 at 19:45

0 Answers0