简体   繁体   中英

How to play randomly chosen music using JS?

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!

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? )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM