javascript - 如何播放页面上的每个音频元素(HTML、JQuery、Javascript)

标签 javascript jquery html audio

好的,我有一个页面,上面有多个音频元素。我正在寻找一种播放每个音频的方法,从第一个开始,等待它完成播放,然后转到下一个音频元素,直到最后一个元素。有什么办法可以实现这一点吗?谢谢!

编辑:

我无法添加代码示例,因为音频元素都是由 PHP 动态添加的,因此在此之前它是一个空文件。

最佳答案

您可以通过将每个音频元素存储在队列中来实现此目的。假设您将每个元素存储在数组 audioElements 中。

var index = 0;
function playNext(index){
  audioElements[index].play(); //this will play the element
  audioElements[index].on('ended', function(){ //this will bind a function to the "ended" event
    //increment the index to target the next element
    index++;
    if(index < audioElements.length){
      //plays the next song and binds the function to the ended event again until the queue is empty
      playNext(index);          
    }
  }
}
playNext(index);

关于javascript - 如何播放页面上的每个音频元素(HTML、JQuery、Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27995654/

相关文章:

javascript - 从 chrome.storage.local 中检索对象并使用它来更改当前页面的 CSS

javascript - 如何更改数据工具提示消息

php - 将价格表从 Excel 复制并粘贴到浏览器

html - 无法摆脱标题的神秘链接

javascript - Vue JS 通过用户输入更新计算属性

javascript - 运行 Screeps 游戏脚本时出错

javascript - 数据库 Jquery - 使用 ScrollY 时列标题未对齐

javascript - 每 30 秒存储一次用户视频进度 Plyr.js

javascript - 我们如何为另一个页面发送隐藏在 php 中的 jquery 金额字段以检索金额值?

javascript - 使用 javascript 函数按 ID 操作多个 div