Play next html5 audio when one above it finishes

2019-08-24 20:07发布

问题:

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>