限制HTML5视频currentTime

时间:2015-03-06 20:28:24

标签: javascript jquery ajax html5 html5-video

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

我遇到的问题,因为视频播放 API报告每个~300MS ,我不想经常点击我的API。所以我需要一个解决方案来跟踪我上次发布的内容。在挖掘之后,我无法找到答案,所以万一其他有类似需求的人,我对此问题的解决方案如下。

1 个答案:

答案 0 :(得分: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视频,因为示例视频无法通过安全连接工作。