Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีเล่น HTML5 Audio แบบสุ่ม


เพื่อเล่นแบบสุ่ม ให้เพิ่มเพลงดังนี้:

init([
  'https://demo.com/songs/song1.mp3',
  'https://demo.com/songs/song2.mp3',
  'https://demo.com/songs/song3.mp3'
]);

ใช้โค้ดต่อไปนี้เพื่อเล่นแบบสุ่มด้วย Math.random:

function displayRandom() {
  var audio = Math.floor(Math.random() * (collection.length));
  audio = collection[audio];
  audio.play();
  setTimeout(loop, audio.duration * 1000);
}