javascript - 如何检查音频是否正在缓冲?

标签 javascript html5-audio

我正在使用 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/

相关文章:

typescript - 如何从 Angular 6 中的 blob URL 下载音频文件?

javascript - YouTube 视频结束后隐藏 div

javascript - 寻找一个正则表达式来替换我的字符串

javascript - knockout 导致无法解析 foreach 循环中的绑定(bind)属性

html - 使用来自音频标签的源使用 AudioContext

javascript - 使用 new Audio(),有什么方法可以找出音频文件是否存在?

javascript - 为什么 onmouseover 有效,但 onkeydown 无效?

javascript - 使用 javascript 调用具有相同参数值的函数

HTML5 : capture audio AND video combined from web browser

javascript - jquery 移动页面导航后音频仍在播放