0

I have button that changes when you press play/pause and I was wondering how should I make it play song randomly.

<a id="play-pause-button" class="fa fa-play"></a>
<script>
var audio = new Audio("audio link");

$('#play-pause-button').on("click",function(){
  if($(this).hasClass('fa-play'))
   {
     $(this).removeClass('fa-play');
     $(this).addClass('fa-pause');
     audio.play();
   }
  else
   {
     $(this).removeClass('fa-pause');
     $(this).addClass('fa-play');
     audio.pause();
   }
});

audio.onended = function() {
     $("#play-pause-button").removeClass('fa-pause');
     $("#play-pause-button").addClass('fa-play');
};
</script>

Thanks in advance!

Barmar
  • 741,623
  • 53
  • 500
  • 612
Tudis
  • 3
  • 1
  • Is there a list of songs somewhere on your webpage? – Barmar Apr 30 '21 at 22:06
  • If you have an array of audio URLs, pick a random element of the array, then use that as the argument in `audio = new Audio(...)` before `audio.play()` – Barmar Apr 30 '21 at 22:08
  • Will this questions help you? - https://stackoverflow.com/questions/37635281/playing-random-sounds-continuously-on-the-page **or** https://stackoverflow.com/questions/39604400/play-a-random-sound-on-single-button – s.kuznetsov Apr 30 '21 at 22:10

1 Answers1

0

your musics probably are in an array, to play music randomly, you have to had the length of that array, and use random function to produce random number in a specific range.(this link will help to generate your numbers: Generating random whole numbers in JavaScript in a specific range?)

ellie
  • 92
  • 1
  • 8