Detect buffering in HTML5 video

Detect buffering in HTML5 video

by Thanos Saringelos

HTML

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<video id='v' controls src="http://thenewcode.com/assets/videos/polina.mp4" type="video/mp4">
</video>

CSS

video {
  width: 400px;
}

JavaScript

var checkInterval = 50.0 // check every 50 ms (do not use lower values)
var lastPlayPos = 0
var currentPlayPos = 0
var bufferingDetected = false
var player = $("#v").get(0);

setInterval(checkBuffering, checkInterval)

function checkBuffering() {
  currentPlayPos = player.currentTime
  console.log(9)
    // checking offset should be at most the check interval
    // but allow for some margin
  var offset = (checkInterval - 20) / 1000

  // if no buffering is currently detected,
  // and the position does not seem to increase
  // and the player isn't manually paused...
  if (!bufferingDetected && currentPlayPos < (lastPlayPos + offset) && !player.paused) {
    console.log("buffering")
    bufferingDetected = true
  }

  // if we were buffering but the player has advanced,
  // then there is no buffering
  if (
    bufferingDetected && currentPlayPos > (lastPlayPos + offset) && !player.paused
  ) {
    console.log("not buffering anymore")
    bufferingDetected = false
  }
  lastPlayPos = currentPlayPos
}