在 html5 音频元素播放结束前 5 秒执行 Javascript 代码

Execute Javascript code 5 seconds before html5 audio element reaches end of playback

我正在使用默认的 audio 元素(不向用户提供控件),我通过 jQuery(更改源,playing/pausing - 通常).现在我正在尝试淡入下一首曲目(第二个音频元素的),提前 5 秒开始播放以实现无缝过渡。

根据我从 media events and audio element attributes 页面收集到的信息,默认情况下不存在执行此操作的方法 - 最接近的似乎是 onended 事件(很明显,它触发得太晚了) ,以及具有相同问题的 loop 属性。

I seperated my previous attempt into an answer to remove the question from the unanswered queue, but it originally was included here

非常感谢以我错过的方式更有效地解决此问题或改进我现有解决方案的任何帮助!提前致谢。

在这一点上,我看到的唯一解决方案是提前检查轨道的持续时间,然后设置以下超时:

$('audio').bind('loadedmetadata', function() {
  duration = $(this).prop('duration') * 1000; // get duration in milliseconds
  var fadetimer = setTimeout(function(){
    // set up next audio file
  }, duration - 5000); // execute timeout 5 seconds before end of playback
});

然而,这对我来说似乎非常低效。我也不确定此方法是否会在后台留下 "garbage" 超时或事件绑定 运行,这最终会加起来并减慢应用程序。