Video.js – Callback a Function in the Event that a Video is 50% Buffered


In this tutorial, we will show how you can get the buffer percentage of a video in video.js and use a callback function when the video has buffered more than 50%. Video.js is a well-known online video player JavaScript toolkit that is used to create web browser video players for a range of video formats. Video.js is a very flexible and customizable library to create modern web video players. It supports a wide range of packages, plugins, and options. Using video.js any part of an HTML video player can be configured as per your liking.

For the purpose of this tutorial, we're going to invoke a callback function when a video is 50% buffered in video.js. First, we're going to learn how to get the buffer percentage of a video using video.js, and then we'll add a callback function to trigger when the video has buffered by 50%. Let's move on to the next section of this tutorial to understand how can we achieve the same using video.js.

Callback a Function in the event that a Video is 50% Buffered

Video buffering is the pre-loading of video segments for streaming the video. This technique has been used by many popular video streaming sites for streaming the video. Some part or segments of the video is preloaded and the video is played so that the end user doesn't have to wait for downloading the complete video.

Prerequisite − Assuming that you know how to create a basic video player using the video.js library.

Video Buffer Percentage is the amount of video buffered out of the total length of the video. We can get the buffer percentage of a video using video.js by making use of the bufferPercentage() method on video player reference. This method return a percentage of video buffered till that specific time in decimal format.

However, the value of buffer percentage changes with the progress of the video i.e. it goes from 0% buffer to 100% buffered depending on how much the video has played, how fast is the bandwidth of the user, etc. So, to keep track of the buffer percentage with the progress of the video, we need to listen to the 'progress' event

Progress Event Listener

The progress event occurs in the web browser whenever a resource is being loaded, i.e., whenever a video or audio is being loaded from a URL or a third-party source, this event is triggered. So, the progress event can be used to track the buffer percentage of our video as soon as the loading progress of a video changes.

You can use this event listener by using 'play' method on the reference of your video.js player using the player.on() method. Callback functions passed (as an argument) to this event listener are going to be executed as soon as the video starts loading.

You will need the following code to use the progress event to get the buffer percentage on the video.js player −

<script>
   // Initializing the video player
   const player = videojs('my-video-player');
   // Buffer Percentage of the video with progress event listener
   player.on('progress', function () {
      const buffPercentage = player.bufferedPercent();
      console.log("Buffer Percentage: ", buffPercentage);
   });
</script>

In the above code excerpt, we've created a video player instance using the videojs() method on the <video> element with id as 'my-video-player'.

Then we used the progress event to capture the changes in the loading state of a video and in the callback function of this event, we used the bufferPercent() method to get the latest percentage of the video that is buffered.

When you execute the above code, the video buffer percentage will be logged in the browser console video as soon as the video is pre-loaded. You'll see multiple logs like this −

Buffer Percentage: 0 
Buffer Percentage: 0.010983981771910626
Buffer Percentage: 0.02974826966353168 
Buffer Percentage: 0.05308923092884176 
Buffer Percentage: 0.0733713463484793 
Buffer Percentage: 0.09037201866684796 
Buffer Percentage: 0.1020040768163907

These are the multiple buffer percentages as the video is being pre-loaded. Since these values are decimal, a buffer percentage of 0.1 means that 10% of the video has buffered.

Now that, we've understood how to get the video percentage of the video, we can now check if the video percentage is above 50% (or 0.5 decimal value) and call a function or do some task basis on that.

Consider the below code snippet for alerting a text on the browser window if the video buffer percentage is more than 50%:

<script>
   // Initializing the video player
   const player = videojs('my-video-player');

   // Buffer Percentage of the video with progress event listener
   player.on('progress', () => {
      const buffPercentage = player.bufferedPercent();
      console.log("Buffer Percentage", buffPercentage);

      if (buffPercentage > 0.5) {
         window.alert('50% of the video has been buffered.');
      }
   });
</script>

As you can see in the above code, we're getting the buffer percentage of the video using the bufferedPercent method. Then we checked if the buffer percentage is greater than 0.5 i.e if the video buffered more than 50%. If that's the case, we've alerted '50% of the video has been buffered.' in the buffered windows.

Instead of alerting something, you can also use a callback function to do a specific task.

Example 1

Using the above code snippet with the complete example for alerting a text in the browser window if the video has buffered more than 50% will look this −

<!DOCTYPE html>
<html>
<head>
   <title>Video.JS Buffer Percentage Example</title>

   <!-- Importing Video.js CSS / JS using CDN URL -->
   <link href="https://vjs.zencdn.net/7.19.2/video-js.css" rel="stylesheet" />
   <script src="https://vjs.zencdn.net/7.17.0/video.min.js"></script>

</head>
<body>
   <video
      id="my-video-player"
      class="video-js vjs-default-skin vjs-big-play-centered"
      preload="true"
      controls="true"
      fluid="true"
      muted="true"
      autoplay="true"
      poster="assets/sample.png"
      data-setup='{}'
      >
      <source
         src="https://vjs.zencdn.net/v/oceans.mp4"
         type="video/mp4"
      >
   </video>
   <script>

      // Initializing the video player
      const player = videojs('my-video-player');

      // Buffer Percentage of the video with progress event listener
      player.on('progress', () => {
         const buffPercentage = player.bufferedPercent();
         console.log("Buffer Percentage", buffPercentage);

         // Check if 50% of the video has been buffered
         if (buffPercentage > 0.5) {
            window.alert('50% of the video has been buffered.');
         }
      });
   </script>
</body>
</html>

In the above code example, we've implemented the following −

  • First, we've used the free CDN URL of video.js to import the required CSS and JS files of video.js in the <head> section of the code.

  • Further, we've created a <video> element inside the <body> section of our code. The <video> element has been initialized with classes like video.js, video-default-skin, and vjs-big-play-centered.

  • The 'id' of the video element i.e. 'my-video-player' has been later used in the <script> section of the code to create a video player for this id.

  • We've also utilized some standard HTML video options like controls, muted, and poster for the <video> element and fluid attribute has been used to make the video player responsive.

  • For the source, we've used an mp4 video, for which we've mentioned the MIME type as video/mp4 in the source tag.

  • In the <script> tag, the video player has been initialized for <video> element having id as 'my-video-player'

After initializing the video player, we used the player.on method to invoke an event listener. The event used is 'progress', which is responsible for invoking the callback function whenever the video is being buffered or preloaded

We then used the bufferedPercent() method on the video player instance to get the current percentage of video buffered and if the video has buffered more than 50%, a text is shown in the browser window.

When you execute the above code in a web browser, it will show '50% of the video has been buffered.' when the video is buffered more than 50%. So, we've successfully learned how to handle the event when a video is 50% buffered in video.js.

Conclusion

In this tutorial, we understood how to capture an event when a video is 50% in video.js. We used the bufferedPercent() method exposed by video.js to get the current buffered percentage of the video. Apart from that, the 'progress' event listener was used to capture the changes in the buffered state of the video. Finally, we showed an alert in the browser window if the video buffer percentage was more than 50%. We also had a look at fully working example for the same.

Updated on: 13-Apr-2023

737 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements