Play next html5 audio when one above it finishes

浪尽此生 提交于 2019-12-11 15:01:49

问题


Hello I have a series of audio clips.

<div class="audio-wrapper">
    <audio controls>
      <source src="aduio1.mp3" type="audio/mpeg">
    </audio>
</div>

<div class="audio-wrapper">
    <audio controls>
      <source src="aduio2.mp3" type="audio/mpeg">
    </audio>
</div>

<div class="audio-wrapper">
    <audio controls>
      <source src="aduio3.mp3" type="audio/mpeg">
    </audio>
</div>

<div class="audio-wrapper">
    <audio controls>
      <source src="aduio4.mp3" type="audio/mpeg">
    </audio>
</div>

In my actual code the audio is spread out through a large wordpress page.

I was wondering if it was possible to play the next one after one above it finishes? For example if one near the top of html is played then it will find the next down and play that, and so one.

For example if someone pressed play on the first one and it finished till the end. The one below it would start playing, and so on.

Another example if someone hit play on the 3rd one and that one finished, Then the 4th one would start playing.

Thanks for any help!

(think podcast site)


回答1:


You can attach ended event to ".audio-wrapper audio" selector, check if $(this).parent(".audio-wrapper").next(".audio-wrapper") exists using .is(), if true, call .play()

const src = "https://upload.wikimedia.org/wikipedia/commons/4/4d/%22Pollinate%22-_Logic_Synth_and_Effects_Demonstration.ogg";

$(".audio-wrapper audio")
.each(function() {
  this.src = src;
})
.on("ended", function(event) {
  let next = $(this).parent(".audio-wrapper")
             .next(".audio-wrapper").find("audio");
  console.log(next)
  if (next.is("*")) {
    next[0].play()
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="audio-wrapper">
    <audio controls>
    </audio>
</div>

<div class="audio-wrapper">
    <audio controls>
    </audio>
</div>

<div class="audio-wrapper">
    <audio controls>
    </audio>
</div>

<div class="audio-wrapper">
    <audio controls>
    </audio>
</div>


来源:https://stackoverflow.com/questions/46702074/play-next-html5-audio-when-one-above-it-finishes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!