在第一个音频播放完毕后播放第二个音频

Play second audio after the first has finished playing

我有以下 HTML:

<audio autoplay id="background_audio">
      <source src="https://sporedev.ro/pleiade/hol.mp3" type="audio/mpeg">
</audio>

上面的代码在后台播放一些音乐。

<audio autoplay>
  <source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>

此代码会在用户进入页面时播放一个 swoosh 声音。

我有以下 JS:

<script>
    var audio = document.getElementById('background_audio');

    document.getElementById('mute').addEventListener('click', function (e)
    {
        e = e || window.event;
        audio.muted = !audio.muted;
        e.preventDefault();
    }, false);
</script>   

此代码用于在用户点击某个div时将背景音乐静音。

这是一个JSFiddle

我正在从事的项目 link 是 here

我正在尝试创建一个脚本,该脚本不会播放位于 background_audio id 中的 audio ,直到 一定的秒数(例如,5s) 已经过去,以便在开始音乐之前可以完成 swoosh 声音的播放。

我对 SO 和 Google 进行了一些研究,得出的结论是 preventDefault() 的某些使用将是解决方案,但我未能实施该解决方案。

如何让background_audioid里的音乐播放完swoosh之后?

您可以使用 onended events,在第一个音频结束后播放第二个音频。

var audio1 = document.getElementById("another_audio");
audio1.onended = function() {
  console.log('Playing background audio')
  var audio2 = document.getElementById("background_audio");
  audio2.play();
};
<audio id="background_audio">
  <source src="https://sporedev.ro/pleiade/hol.mp3" type="audio/mpeg">
</audio>

<audio autoplay id="another_audio">
  <source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>