如何在当前音频播放完后播放下一首音频?

How to play next audio when the current audio is finished playing?

如果当前音频播放完毕,我目前正在尝试播放另一个音频,但我没有获得任何成功结果,如果给出任何建议,我将不胜感激,这是下面的代码:-

document.addEventListener('DOMContentLoaded', () => {

  ms();

});

function ms() {
  var btns = document.getElementsByClassName("pas");
  for (var j = 0; j < btns.length; j++) {

    document.addEventListener('play', function(e) {
      var songs = document.getElementsByClassName("pas");
      for (var i = 0; i < songs.length; i++) {
        if (songs[i] != e.target) {
          songs[i].pause();
        }
      }

    }, true);


  }

}
<audio class="pas" controls loop autoplay>
  <source  src="https://www.mboxdrive.com/Drake_-_One_Dance_(Lyrics)_ft._Wizkid_&_Kyla(128k).m4a" type="audio/mp3">
    Your browser dose not Support the audio Tag
</audio>
<audio class="pas" controls loop autoplay>
  <source src="https://www.mboxdrive.com/Coobie_-_Miss_You_(Official_Lyric_Video)(256k).mp3" type="audio/mp3">
    Your browser dose not Support the audio Tag
</audio>

以上js是只允许一个音频播放一次。如果第一个音频完成,是否可以添加任何功能来播放另一个音频?

您可以在此处尝试代码演示 https://jsfiddle.net/mt1koznd/2/

使用 timeupdate 事件,以及 .duration.currentTime 属性。如果你打算切换玩家,你需要移除 loop 属性并移除所有玩家的 autoplay 属性,但一个或所有玩家将同时玩。该示例适用于无限数量的玩家,如果当前玩家是最后一个玩家,将循环回到起始玩家。

详情见示例

<!DOCTYPE html>
<html lang="en">

<head>
  <title></title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <style></style>
</head>

<body>
  <audio class="song" controls>
  <source  src="https://www.mboxdrive.com/Drake_-_One_Dance_(Lyrics)_ft._Wizkid_&_Kyla(128k).m4a" type="audio/mp3">
</audio>
  <audio class="song" controls>
  <source src="https://www.mboxdrive.com/Coobie_-_Miss_You_(Official_Lyric_Video)(256k).mp3" type="audio/mp3">
</audio>
  <script>
    // Collect all .song into a NodeList then convert it into a real array
    const songs = [...document.querySelectorAll('.song')];

    // Bind the timeupdate event to each .song
    songs.forEach(song => song.ontimeupdate = nextSong);
    
    // Event handler
    function nextSong(e) {

      // Get player's full duration in seconds
      const end = this.duration;

      // Get the current time spent playing in seconds
      let now = this.currentTime;

      // If the time playing reaches the duration...
      if (end <= now) {
        
        // Get the index position of player
        const position = songs.indexOf(this);

        // If the player is the last one start play on the first player
        if (position === songs.length - 1) {
          songs[0].play();

        // Otherwise start ply on the next player
        } else {
          songs[position + 1].play();
        }
      }
    }
  </script>
</body>

</html>