0

I'm trying to make an MP3 random player. I've already done every array and cycles, but what it struggles me is that every songs plays all in the same time, basically something like that:

var num; var x = 0; let music = ['https://samplelib.com/lib/previeww/mp3'sample-3s.mp3', 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3']; funcion button(){ for (let i = 0; i < 4; i++){ num = Math.floor(Math.random()*3);

console.log(num);} music.play(num)} music[num].addEventListener('ended', console.log("placeholder")});

What happens, as I porevious said before, the cycle doesn't wait the sound to finish, it goes back over and over again until the page crashes. Is there any way to make him wait before it plays again?

  • 1
    It could be more helpful; if you provide the code of what you're tried; with that we could spot the error more easily! – XMehdi01 Oct 27 '21 at 20:35
  • 2
    Your question is too broad, seeing as you haven't really tried anything with respect to waiting out the track. Here's a start: https://stackoverflow.com/questions/4619917/how-to-detect-an-audio-has-finished-playing-in-a-web-page – isherwood Oct 27 '21 at 20:35
  • Welcome. Please see [ask] and take the [tour]. – isherwood Oct 27 '21 at 20:37
  • Yeah, I've tried addEventListener, but for some reason I cannot use do-While cycle inside (for what I've tried so far). Anyway I'm updating my question with my code – Arisyn ILY Oct 27 '21 at 20:38

1 Answers1

0

You're going to need to provide more context for us to give you a really good answer.

My guess is that whatever function you're calling in the for loop is happening asynchronously. Basically, your for loop may be pushing the start button 4 times in a row without waiting for the end to happen.

If you look at the documentation for your mp3 player object/function that you're calling in the for loop you may be able to identify a function that checks when the song is over and then wait for that before you call the next iteration of the for loop

Adam DP
  • 36
  • 3