Home » Javascript » Randomize javascript audio variable on music finish

Randomize javascript audio variable on music finish

Posted by: admin August 19, 2018 Leave a comment

Questions:

I have a start and stop buttons and I’m trying to randomize the song that will be played next if the start button is just pressed 1 time, but I keep getting the same music to be played over and over.

It randomizes fine if I press start, stop and start again, but not when the music finishes by herself – can somebody tell me what is wrong with the code?

var sounds = [
        "sounds/royksopp.mp3",
        "sounds/9thwonder.mp3",
        "sounds/thisbeat.mp3",
        "sounds/mosdef.mp3",
        "sounds/bewater.mp3",
        "sounds/boutdre.mp3",
        "sounds/masterflash.mp3",
        "sounds/2ep.mp3",
        "sounds/drewestcoast.mp3",
        "sounds/poetry.mp3",
        "sounds/mfdoom.mp3",
        "sounds/imnot.mp3",
        "sounds/jamba.mp3",
        "sounds/meetyour.mp3",
        "sounds/popyacork.mp3",
        "sounds/dreams.mp3",
        "sounds/unders.mp3",
        "sounds/oizo.mp3",
    ];

function StartOrStop(audioFile) {
    srcAudio = sounds[Math.floor(Math.random() * sounds.length)];
    var audie = document.getElementById("myAudio");
    audie.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
    }, false);

    if (audie.paused == false) {
        audie.pause();
    } else {
        audie.src = sounds[Math.floor(Math.random() * sounds.length)];
        audie.play();
    }
}
Answers: