Calculate the percentage of YouTube videos watched using the API

I am creating an online video and online exercise course and would like people to be able to log in and track their progress.

Is there a way I could measure the percentage of youtube embedding that someone watched and mark it as complete if they looked at, say, more than 80%?

My best idea so far is to use getCurrentTime () when the playerโ€™s state changes to PLAYING, and then again every five seconds or so, adding a difference in some amount. However, if someone watched the first minute five times, they would end the shot, although they did not see it all.

Is there a more elegant solution to calculate the% of the video you are watching, rather than the method described above, which calculates the amount of time spent watching the video?

+5
source share
2 answers

How about something like this:

        var i; //Global variable so that you can reset interval easily

        function onYouTubePlayerReady(playerid) 
        {
            ytp = document.getElementById("ytvideo"); //get player on page
            ytp.d = ytp.getDuration(); //get video duration
            i = setInterval(checkPlayer, 5000); //check status

        }

        function onplayerReset() 
        {
            clearInterval(i);
        }

        function checkPlayer()
        {
            var p = ytp.getCurrentTime(); //get video position
            var d = ytp.d; //get video duration
            var c = p/d*100; //calculate % complete
            c = Math.round(c); //round to a whole number
            var t = document.getElementById('videotitle').innerHTML;

            if(ytp.isReset) { c = 0; }
            ytp.c=c;

            if(!ytp.completed) 
            {   
               if(c>=80) { _gaq.push(['_trackEvent', 'Video Status', t,'Complete']); ytp.completed=true; } // or do something else
            }

         }
+3
source

I use the Angular module for embedding YouTube for AngularJS (here you can find https://github.com/brandly/angular-youtube-embed ). But this solution will work the same for Javascript / YouTube API calls. I just don't want to rewrite my decision.

, . 10 . 5 , . , , .

getPctCompleted() , , .

, . "", - -. , .

       $scope.analyzer = {};
       $scope.timeElapsed = 0;
       $scope.videoLength = 0;

       $scope.$on('youtube.player.playing', function($event, player) {
           $scope.videoLength = player.getDuration();
           $scope.player = player;
           //start polling
           setInterval(function() {
                $scope.timeElapsed = $scope.player.getCurrentTime();
                $scope.analyzer[parseInt($scope.timeElapsed / 10)] = true;
                $scope.$apply();
           }, 5000);
       });

       $scope.getPctCompleted = function() {
           return Object.keys($scope.analyzer).length / (parseInt($scope.videoLength / 10));
       };
+2

All Articles