如何在JavaScript中播放另一个声音文件后播放声音?

3
如何在一个声音结束后播放另一个声音文件?如果我这样做:
first.play();
second.play();

两个声音同时播放。我想要先播放first.play(),当它结束时,再开始播放second.play()

4个回答

4
first.addEventListener('ended', function(){
    second.play();
});
first.play();

但是,如果我想连续播放许多文件,我将会陷入回调地狱。有没有办法引入.then()的Promise语法? - whamsicore
@whamsicore,请看一下我的答案,它使用了.then()。 - jo3rn

0

我建议使用某种方式:

// if using jQuery:
var audios = $('audio');

audios.each(function(idx){
    $(this).bind('ended', function(){
        var next = audios.get(idx+1);
        if(next){
            next.get(0).play();
        }
    });
});

0

我使用了 AudioScheduledSourceNode.onended

我使用了四个声音,并将此代码放入一个函数中:

sound1.play();
sound1.onended = function () {
    sound2.play();
};
sound2.onended = function () {
    sound3.play();
};
sound3.onended = function () {
    sound4.play();
}

这是应用程序的实时链接:insultinator-toy.netlify.app

点击问号按钮。

以及指向丑陋源代码的链接。 jsahlsa


0

你也可以使用带有超时的 Promise:

const playPromise = first.play()

playPromise.then(() => {
    setTimeout(() => {second.play()}, first.duration * 1000)
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接