Home > Software engineering >  Cannot access video load progress in Javascript
Cannot access video load progress in Javascript

Time:10-28

I'm trying to make a video player with several features by js html and css, but when I came to trying to preload the video, I couldn't find a way to know how much of the video was downloaded, and I need to know this info so I can update a progress bar to tell how much data has been buffered.

Is there a way to find out how much a video has been buffered?

I tried accessing the video preload property in javascript to get how much it was preloaded . but it gave me the preload type of the video

CodePudding user response:

You need to use: TimeRanges to know the length of loaded (buffered) video.
There will be more time ranges added if you seek into a new area that has not yet buffered. Either handle such situation or else code your UI to not respond if a user clicks outside the fill area (eg: only clicking within fill area will change currentTime of video).

Also read: Media buffering, seeking, and time ranges guide for more knowledge.

Below is some testable code as a starting point to expand:

<!DOCTYPE html>
<html>
<body>

<video id="myVid" width="320" height="240" controls>
  <source src="your_file.mp4" type="video/mp4">
</video>

<br><br>

<div id="myProgress_BG" style="width: 320px; height: 30px; background-color: #808080">
  <div id="myProgress_Bar" style=" width: 1%; height: 30px; background-color: #00A0E6" ></div>
</div>

</body>

<script>

let timeLoaded = 0; let timeTotal = 0;

//# access the "fill" (blue) bar
let prog_Bar = document.getElementById('myProgress_Bar');

//# get the max width for the "fill" (is same as BG width)
let prog_Max = document.getElementById('myProgress_BG').style.width;
prog_Max = parseInt(prog_Max);

//# set a listener for the "progress" event
let vid = document.getElementById('myVid');
vid.addEventListener('progress', (event) => { myProgressFunc() });

function myProgressFunc()
{
    //# update times (duration and buffered)
    if( timeTotal == 0 ) { timeTotal = vid.duration; }
    timeLoaded = vid.buffered.end(0);
    
    //# update width via CSS Styles (numbers need a  "px" to work)
    prog_Bar.style.width = ( prog_Max / ( timeTotal / timeLoaded) )  "px";
}

</script>

</html>
  • Related