1
votes

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!

1
And the problem is? You only have to change the .src of the <audio /> element (+ some "waiting..." until the browser is able to actually play the file.Andreas
"Sort of like lazy loading for audio files?" - It works the same way as with images.Andreas
Thanks, but that is just an additional question. My main question is how do I make an array of mp3 files?ixcode
This would then be question number three. And no, your "main question" is the one from the title. At least that's how SO works ;)Andreas

1 Answers

1
votes

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>