ixcode
ixcode

Reputation: 653

How to play an audio randomly from an array of mp3 using javascript

I have here a button, where if a user presses it, will play a background music. If pressed again, it will then pause the music.

This works fine for single mp3 file, but I wanted to add more songs for variation.

I don't want to make it a complicated music player. Just a single button that play/pause the music and when bg1 is done, play next one in the array.

Also, I'm hoping if the music to played could be selected at random?

Please take a look at what my code looks like so far:

var myAudio = document.getElementById("myAudio");
    var isPlaying = false;

    function togglePlay() {
      isPlaying ? myAudio.pause() : myAudio.play();
    };
    
    myAudio.onplaying = function() {
      isPlaying = true;
    };
    myAudio.onpause = function() {
      isPlaying = false;
    };
<audio id="myAudio" src="bg1.mp3" preload="auto" loop></audio>

<a href="#" onclick="togglePlay()">Play Music</a>

And here's my trial script for array, but I cannot finish it myself

let musicPlayer=[

`bg1.mp3`,
`bg2.mp3`,
`bg3.mp3`,
`bg4.mp3`

];

function playMusic(){

    let index=Math.floor(Math.random()*musicPlayer.length);
    
    let div=document.querySelector('#music');

Lastly, I'm planning to make an array of about 70 mp3 files which can cause long loading time. Can it be made so that it won't load until its turn. Sort of like lazy loading for audio files?

I would really appreciate it. Thanks a lot in advance!

Upvotes: 2

Views: 1582

Answers (1)

J&#243;zef Podlecki
J&#243;zef Podlecki

Reputation: 11283

I would tackle it following way.

const audio = document.querySelector('#audio');
const audioButton = document.querySelector('#audioButton');

const audioUrls = [
"https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
];

const randomAudio = () => {
  const index = Math.floor(Math.random() * audioUrls.length);
  const audioUrl = audioUrls[index];
  
  return audioUrl;
}

audioButton.addEventListener("click", () => {
  audio.addEventListener("ended", () => {
    const audioUrl = randomAudio();
    
    const temp = new Audio();
    
    temp.addEventListener("loadeddata", () => {
      audio.src = audioUrl;
  });
    
    temp.src = audioUrl;
  })
  
  const audioUrl = randomAudio();
  
  audio.addEventListener("loadeddata", () => {
      audio.play();
  });
  
  audio.src = audioUrl;
  
})
<audio id="audio" src="" preload="auto" loop></audio>

<a id="audioButton" href="#">Play Music</a>

Upvotes: 1

Related Questions