【问题标题】:How can I let music autoplay only when play Button triggerd?如何让音乐仅在播放按钮触发时自动播放?
【发布时间】:2019-10-13 11:52:57
【问题描述】:

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

下面的代码工作正常,除了前面提到的,音乐自己播放,没有按下播放按钮。有谁知道如何解决这个问题?

我尝试将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>

【问题讨论】:

  • selectRandom(); 移动到按钮点击事件并移除 player.play(); // 开始歌曲
  • 能否请您提供按钮单击事件的代码,因为我还是个初学者。提前谢谢你。

标签: javascript html


【解决方案1】:

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

麦丁

【讨论】:

  • 是的。音乐在开始时仍会自行播放。
  • 替换 player.play();与 player.pause();如果您想使用内部播放按钮,可以为您提供帮助。
  • 你的权利!这是我正在寻找的sloution。很简单。谢谢!
【解决方案2】:

创建一个按钮并添加一个onclick属性,移动selectRandom() 到按钮onclick 功能如下:

var player = document.getElementById("audioplayer");
var lastSong = null;
var selection = null;
var playlist = ["https://www.soundjay.com/button/sounds/beep-07.mp3", "https://www.soundjay.com/button/sounds/button-2.mp3", "https://www.soundjay.com/button/sounds/button-3.mp3"]; // List of Songs

function start() {
   player.play();
   player.addEventListener("ended", selectRandom);
   
    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

    }
    player.autoplay=true;
    selectRandom();
}
<audio id="audioplayer" controls ></audio>

<button onclick="start()"> Play </button>

【讨论】:

  • 这对我不起作用,它只播放音频标签中的歌曲并且以相同的顺序播放。
  • 然后删除音频标签上的src,我没有更改您的代码。我编辑了我的答案,现在试试。
  • 太好了,它有效!唯一的问题是我不能使用音频栏的控件来播放音乐(我必须使用播放按钮)并且我不能使用播放按钮来停止音乐。 (我必须使用音频栏暂停按钮)
  • 我喜欢我可以使用播放按钮来播放不同的歌曲。
  • 非常感谢您的帮助。我喜欢海狸!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-30
  • 1970-01-01
相关资源
最近更新 更多