如何在页面上播放每个音频元素(HTML,JQuery,Javascript)

How to play each audio element on a page (HTML, JQuery, Javascript)

本文关键字:HTML 元素 JQuery Javascript 音频 播放      更新时间:2023-09-26

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

编辑:

我无法添加代码示例,因为音频元素都是由 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);

基于@liam-Schauerman的回答,我实际上提出了这个解决方案:

var index = 0;
var audioElements = document.getElementsByTagName('audio');
function playNext(index) {
    audioElements[index].play();
    $(audioElements[index]).bind("ended", function(){
        index++;
        if(index < audioElements.length){
            playNext(index);          
        }
    });
}
$(document).ready(function() {
    $("#swig").click(function() {
        audioElements[index].play();
        $(audioElements[index]).bind("ended", function(){
             index = index + 1;
             if(index < audioElements.length){
                playNext(index);          
             }                        
        });

    });
});

我只是盲目地编码了这个。如果有人详细说明以及为什么这样做,我将不胜感激。