Tracking Video Watching Behavior using Youtube API

This post offers a simple introduction to recording the student’s video watching behavior for Youtube videos. Youtube has an enormous amount of educational videos that can be embedded easily in learning applications (e.g. web, desktop). As research (Ozan & Ozarslan, 2016) has shown that the video watching behavior contains rich traces of learning behavior, therefore, it will be of great benefit if we can utilize the availability of Youtube resources with the potential of analytics on video watching behavior to improve the learning experience.

In addition, this post also introduces a Moodle Plugin- VidTrack (link) which can be used to embed Youtube videos in Moodle’s courses and to record student’s video-watching behavior.

Youtube Player API

Youtube offers a Player API which allows the programmer to do the various tasks with Youtube videos ranging from loading video to capturing events. We will use this API to load a Youtube video and capture the video events (e.g. pause, start). Let’s begin with a simple example of this API. We will write a simple HTML file with javascript code to demonstrate the event-capturing mechanism.

<html>
  <head><title> First Example </title></head>

  <body>
    <!-- here we will show the captured info -->
    <div id="demo"></div>

   <!-- here youtube will load the video -->
    <div id='player'></div>

   <script>
   <!-- here we will insert javascript code

                        -->
   </script>
 </body>
</html>

In the above code, we have created a div section with id=player which will be replaced by Youtube player. Another div section we will use to display the tracked states of Youtube Player. Now, let’s load the Youtube Player API.

 // Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  // Replace the 'player' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
      height: '360',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
           'onStateChange': onPlayerStateChange
          }
    });
}

The above code will be placed in our HTML file after <script> tag. The first line in the code var tag = document.createElement(‘script’); creates a script tag to load Youtube API. The second line tag.src = “https://www.youtube.com/player_api”; sets the Player API URL to src attribute of the newly created script tag. Next line var firstScriptTag = document.getElementsByTagName('script')[0]; search script tags and return the first one. As in our code, there is only one script tag, therefore this is returned by the function call document.getElementsByTagName('script')[0]. The next two lines then insert a new script tag for Youtube API just before our script tag (which we have written in html file).

When the Youtube Player API is downloaded completely, function onYoutubePlayerAPIReady() is called. In this function, we have created a Youtube Player object using YT.Player(). Here, we need to specify the id of <div> tag which will be used to display Youtube Video. Additionally, we also need to specify height, width, videoId and events. The height and width for the player will be specified in the first two attributes. In videoId, we need to specify the id of Youtube video we want to play. Finally, in events we need to specify the events (which we want to capture) and their corresponding functions. These functions will be called when that particular event happens. Following are the list of such events provided by Youtube API.

Events Description
onReady This event is fired when the player is ready.
onStateChange This event is fired when the state of player get changed e.g. video stopped, paused, finised. Youtube Player has six states represented by numbers -1 (unstarted) 0 (ended) 1 (playing) 2 (paused) 3 (buffering) 5 (video cued) For more details refer this
onPlaybackQualityChange This event is fired when the video quality is changed in the player.
onPlaybackRateChange This event is called when playback rate is changed in the player.
onError This event is fired when an error occured while playing the video e.g. requested video is not found.
onApiChange This event is fired when player load some modules with exposed API. More details

In the above mentioned events, we have used onStateChange event in our script. We have specified function onPlayerStateChange as event handler for onStateChange. Now, we will write this function to capture and display youtube video’s events.

 function onPlayerStateChange(event) {

       var state=event.data;
       document.getElementById("demo").innerHTML="

State: "+event.data+" Timestamp:"+player.getCurrentTime()+"

"; }

This function simply shows the updated state of Player in the <div> with id=demo.

Execution result

Saving captured information on server

So, the above demonstration simply shows the captured event’s information on the same page. It would be more beneficial if we could store this information on server. I used php to store the same information on server. I did some changes to onPlayerStateChange function.

 function onPlayerStateChange(event) {
       var xhttp;
       var state=event.data;
       //document.getElementById("demo").innerHTML="State changed "+event.data+player.getVideoUrl()+player.getCurrentTime()+" "+course;

       xhttp = new XMLHttpRequest();
       xhttp.open("GET", "add_data.php?state="+state+"&video="+video+"&time="player.getCurrentTime()", true);
       xhttp.send();
  }

I used here XMLHttpRequest() to send the data to server. I simply send a HTTP request to add_data.php with parameters state,time,and video.

A simple php code is given below which simply extracts values of GET paramters. Its functionality can be extended as per your requirements. You can save the received information in database or in csv file.


<?php
 // get value from time parameter
 $time=$_GET['time'];

 // get value from video parameter
 $video=$_GET['video'];

 // get value from state parameter
 $state=$_GET['state'];

$temp='';
switch($state){
    case -1:
        $temp='unstarted';
        break;
    case 0:
        $temp='ended';
        break;
    case 1:
        $temp='playing';
        break;
    case 2:
        $temp='paused';
        break;
    case 3:
        $temp='buffering';
        break;

    case 5:
        $temp='video cued';
        break;
    default:
        $temp='unrecognized state';
        break;

}

// here you can write code to save into database.

?>

Embedding Youtube Videos in Moodle and Capturing Student’s Watching Behavior

I have developed a small Moodle Plugin- Vid_Track (github) which will allow you to embedd Youtube videos in Moodle resources and also to capture and store the student’s watching behavior. The current version stores course-id, video-id, student-id, video-event , and time in Moodle database in the table with name mdl-youtube.

Demonstration of VidTrack Plugin

A complete demonstration from installation to usage is given below.

References

  1. Ozan, O., & Ozarslan, Y. (2016). Video lecture watching behaviors of learners in online courses. Educational Media International, 53(1), 27-41.
 

Pankaj Chejara