Is a jquery callback available after .play() when

2019-01-26 22:32发布

Guys how do I play an mp3 file and then another once the first has finished?

I have tried the following without success..

$('#file1)[0].play( function () {
   $('#file2)[0].play();
});

Can you use callbacks when playing audio?

4条回答
Luminary・发光体
2楼-- · 2019-01-26 22:51

According to W3Schools, you can use the onended event to detect if the HTML5 audio has finished playing.

In jQuery:

$("#player").bind('ended', function(){
    // done playing
    alert("Player stopped");
});

For a demonstration see: http://jsfiddle.net/9PCEf/2/

You can do the rest after audio playing finished.

查看更多
贪生不怕死
3楼-- · 2019-01-26 23:04

You are not calling a jQuery method to begin with.

You could attach an event handler to the "onended" event:

var file = $("#file1");

file.on( "ended", function(){
    $("#file2")[0].play();
});

file[0].play();
查看更多
对你真心纯属浪费
4楼-- · 2019-01-26 23:04

You need to listen to the onended event.

查看更多
Melony?
5楼-- · 2019-01-26 23:08

I used @blasteralfred's code to create a function to play a indefinite series of sound files using jQuery:

function playSounds(soundFileIds) {
  if (soundFileIds instanceof Array) {
    var soundFileId = soundFileIds.shift();
    playSound(soundFileId);
    $(soundFileId).bind('ended', function() {
      playSounds(soundFileIds);
    });
  } else {
    playSound(soundFileIds);
  }
}

The conditional test for an array allows me to backport this to my existing code that calls this function with just a string. Thanks!

查看更多
登录 后发表回答