通过video.js统计实际观看视频时长

1.引入video.js和video.css

下载地址:https://download.csdn.net/download/king2wang/10715735

2.html页面

<video id="demo-video" class="video-js vjs-default-skin" src="视频地址" controls  preload="none"></video>
<input type="text" id="aa" value="0"> {{--观看时长--}}

3.js

$(document).ready(function () {
    var options = {
    };
    var player = videojs('demo-video', options, function onPlayerReady() {
        var time1;
        var t1 = 0;
        function aa() {
            t1 += 0.25;
            document.getElementById('aa').value = t1;
            console.log('aa-' + t1);
        }
        //开始播放视频时,设置一个定时器,每250毫秒调用一次aa(),观看时长加2.5秒
        this.on('play', function () {
            console.log('开始播放');
            time1 = setInterval(function () {
                aa();
            }, 250)
        });
        //结束和暂时时清除定时器,并向后台发送数据
        this.on('ended', function () {
            console.log('结束播放');
            window.clearInterval(time1);
            countTime();   //向后台发数据
        });
        this.on('pause', function () {
            console.log('暂停播放');
            window.clearInterval(time1);
            countTime();  //向后台发数据
        });
    });
    //直接关闭页面,并向后台发送数据
    if(window.addEventListener){
        window.addEventListener("beforeunload",countTime,false);
    }else{
        window.attachEvent("onbeforeunload",countTime);
    }
})

function countTime() {
            var sTime = $("#aa").val();
            $.ajax({
                url : "{{ route('time') }}",
                type : "POST",
                dataType : 'json',
                data : {'sTime':sTime,'_token':"{{ csrf_token() }}"},
                success:function (data) {
                    console.log(data);
                }
            })
        }

猜你喜欢

转载自blog.csdn.net/king2wang/article/details/83001087