我正在使用 new Audio()
创建音频元素,但是当添加事件监听器 'waiting'
时,当我按下播放并执行操作时,它会立即触发当它开始缓冲时实际上并没有触发。
代码:
var source = new Audio('some-url');
source.addEventListener('waiting', function () {
alert('Buffering');
};
source.play()
所以'waiting'
立即触发,但当音频在播放后开始缓冲时它不会再次触发,但是如果我寻找轨道(即使在本地主机上)它也会触发一次。我怎样才能做到这一点?
最佳答案
您在 waiting
事件中看到的行为符合 Mozilla 文档 ( https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events ) 的预期:
waiting
Sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek).
要获取媒体下载的进度,您需要监听一次性事件的 loadstart
或重复事件的 progress
:
loadstart
Sent when loading of the media begins.
progress
Sent periodically to inform interested parties of progress downloading the media. Information about the current amount of the media that has been downloaded is available in the media element's buffered attribute.
var source = new Audio();
source.addEventListener('waiting', function () {
window.alert('Waiting');
};
source.addEventListener('loadstart', function () {
window.alert("Loading");
};
source.addEventListener('progress', function () {
// do something, eg:
var timeRanges = source.buffered;
if (timeRanges && timeRanges.length > 0) {
console.log(timeRanges);
// do something with the TimeRanges object
}
};
source.play()
关于javascript - 如何检查音频是否正在缓冲?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35815423/