【问题标题】:Throttling HTML5 Video currentTime限制 HTML5 视频 currentTime
【发布时间】:2015-03-06 20:28:24
【问题描述】:

我有一个应用程序可以跟踪视频观看次数并将其与其他营销活动集成。这样做时,我需要跟踪一个人观看 html5 视频的时长并将其发布回我的应用程序(通过 API)。我正在使用videojs 播放器,但实际上这只是该属性的 HTML5 api 的包装。这是在一个应用程序中,可以根据他们正在观看的页面加载各种视频,因此我需要一个无论视频长度如何都可以跟踪的解决方案。

我遇到的问题是,当视频播放时,API 报告每 300 毫秒返回一次,我不想经常访问我的 API。所以我需要一个解决方案来跟踪我上次发布的时间。在挖掘之后,我找不到答案,所以如果其他人有类似的需求,我对这个问题的解决方案如下。

【问题讨论】:

    标签: javascript jquery ajax html html5-video


    【解决方案1】:

    我们决定每 5 秒发布一次我的视频观看结果,但由于我们无法保证 currentTime 会在 5 秒时准确报告,所以我们只需四舍五入到最接近的整数值。

    在我的视频包装器 div 上,我添加了一个名为 data-last-time-push 的数据属性。我每次推送时都会发布四舍五入的时间,并检查我们是否超过了再次发布之前的间隔。

    HTML

    <div id="video-wrapper" data-time-last-push="0">
    

    Javascript

    将 videojs 容器绑定到 timeupdate 属性。

        var vid = videojs("video-container", {}, function() {
            this.on('timeupdate', videoTracker);
        });
    

    发布ajax功能...

    var videoTracker = function() {
        var player = this;
        var last_push, wrapper, current;
        wrapper = $('#video-wrapper');
        last_push = wrapper.attr("data-time-last-push");
        current = Math.round(player.currentTime());
        //you could make the 5 here to be a variable or your own interval...
        if (current%5 === 0) {
            if (current > last_push) {
                //do your AJAX post here...
                wrapper.attr("data-time-last-push", current);
                console.log('currentTime = ' + player.currentTime());
                console.log(' duration: ' + player.duration());
            }
        }
    };
    

    注意,我试图做一个 jsfiddle 来展示它的工作,但最终遇到了 HTTPS 视频,因为示例视频不能通过安全连接工作。

    【讨论】:

    • 你可能想先切掉current 的十进制值,比如if (!(current&gt;&gt;&gt;0) % 5) {...} 这会给你整个整数秒来检查。当然,更新 last_push 以免每秒进行 25/30 次检查。或者它可能没有必要,因为 current 总是会在一秒钟内有一个干净的开始(可能除了基于 NTSC 29.97 的视频,具体取决于浏览器如何处理它)。无论如何只是一个想法.. :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 2015-04-03
    相关资源
    最近更新 更多