javascript - 如何让音乐仅在播放按钮触发时自动播放?

标签 javascript html

我正在尝试在我的网站上实现一个音频栏,它可以从歌曲列表中随机选择要播放的歌曲。音乐应该开始,但仅当按下播放按钮时才开始,当一首歌曲结束时,自动播放下一首歌曲。

下面的代码工作正常,除了前面提到的,音乐自行播放而无需按下播放按钮。有人知道如何解决这个问题吗?

我尝试将 player.autoplay=true; 设置为 false 但下一首歌曲不会自动播放。

<audio id="audioplayer" controls> <!-- Remove the "Controls" Attribute if you don't want the visual controls -->
</audio>

<script>
    var lastSong = null;
    var selection = null;
    var playlist = ["sounds/0.mp3", "sounds/1.mp3", "sounds/2.mp3"]; // List of Songs
    var player = document.getElementById("audioplayer"); // Get Audio Element
    player.autoplay=true;
    player.addEventListener("ended", selectRandom); // Run function when song ends

    function selectRandom(){
        while(selection == lastSong){ // Repeat until different song is selected
            selection = Math.floor(Math.random() * playlist.length);
        }
        lastSong = selection; // Remember last song
        player.src = playlist[selection]; // Tell HTML the location of the new Song

    }

    selectRandom(); // Select initial song
    player.play(); // Start Song
</script>

最佳答案

您是否尝试过删除 播放器.play();

马丁

关于javascript - 如何让音乐仅在播放按钮触发时自动播放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363316/

相关文章:

javascript - 向数组添加元素不会增加其长度

javascript - 有没有办法在 HAML 的 :javascript region? 中使用 Ruby 循环

javascript - 为什么只有第一个鼠标悬停和鼠标移开有效?

javascript - 仅允许输入字段中的某些字符

javascript - 如何运行使用 jquery.load() 加载的页面中包含的 javascript 代码

html - 如何创建不同尺寸的圆形图像

javascript图像动画在两个图像之间闪烁

javascript - Expand div双效JQuery中的展开按钮

html - Div 出现在标题上方

javascript - (带有 bodyParser 的 Node :5132) DeprecationWarning: `DEBUG_FD` is deprecated.