结束时随机播放的歌曲 - javascript html5

时间:2017-10-18 21:19:54

标签: javascript html5

我有这个代码随机化并播放一个列表中的歌曲:

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/dreams.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 = srcAudio;
        audie.play();
    }
}

当歌曲停止播放时,它会以相同的歌曲重新开始播放。如何在音乐结束时这样做,它会从我的列表中获取一首新歌并自动播放?

1 个答案:

答案 0 :(得分:1)

问题是您只是在this.play()事件监听器中调用ended。相反,您应该使用src随机选择歌曲来更新this.src = srcAudio属性,类似于初始选择的方式:

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

    if (audie.paused == false) {
        audie.pause();
    } else {
        audie.src = srcAudio;
        audie.play();
    }
}

希望这有帮助! :)