Search code examples
javascriptjqueryaudiorandomjplayer

Randomised Audio List is not playing when called


Functionality:

Random Audio is played in gamepage for a period of 25 seconds, before audio is stopped at the 26th seconds.

What has been done:

I have created an array list for the audio files, a randomised method to randomised the audioList and lastly, to play the random audio.

Issue:

The audio is not playing and the following error msg is shown;

Index.html:1221 Uncaught TypeError: PlaySound.play is not a function

 var audioList = ["lib/audio/Awesome.mp3", "lib/audio/Excellent.mp3", "lib/audio/Fantastic.mp3", "lib/audio/Great.mp3", "lib/audio/KeepitUp.mp3", "lib/audio/MatchGame.mp3", "lib/audio/MatchSpot1.mp3", "lib/audio/MatchSpot3.mp3"];


 $('#DefaultGamePage').fadeIn({
       duration: slideDuration,
       queue: false,
       complete: function() {

         $('#DefaultGameTimer').show();

         //Play Randomised Audio
         var random_Play Audio = Math.floor(Math.random() * (audioList.length));
         var PlaySound = audioList[random_PlayAudio];
         PlaySound.play();
         ...(other game method)..
       },
       1000)
<div id="GamePage" style="display:none; position:absolute; z-index:20; top:0px; left:0px; width: 1080px; height: 1920px; margin:auto;">

  <audio id="Play"></audio>
</div>


Solution

  • audioList is not an audio element but array and it do not have method play()

    Set the src property of the AudioElement as random audion file and Use play() method over element having id as play.

    Try this:

    var audioList = ["lib/audio/Awesome.mp3", "lib/audio/Excellent.mp3", "lib/audio/Fantastic.mp3", "lib/audio/Great.mp3", "lib/audio/KeepitUp.mp3", "lib/audio/MatchGame.mp3", "lib/audio/MatchSpot1.mp3", "lib/audio/MatchSpot3.mp3"];
    
    var playElem = $('#Play').get(0); //select audio element
    
    var handler = function() {
      var random_PlayAudio = Math.floor(Math.random() * (audioList.length));
      playElem.src = audioList[random_PlayAudio];
      playElem.addEventListener("ended", handler); //on end of the audio, execute `handler` again
      playElem.play();
    };
    
    
    $('#DefaultGamePage').fadeIn({
      duration: slideDuration,
      queue: false,
      complete: function() {
        $('#DefaultGameTimer').show();
        handler();
      }
    });
    <div id="GamePage" style="display:none; position:absolute; z-index:20; top:0px; left:0px; width: 1080px; height: 1920px; margin:auto;">
      <audio id="Play"></audio>
    </div>