Can I preload the entire source of HTML5 video before playing?

Decision

I created a working example of an accepted answer that uses XHR and reports the progress of the download through the panel.

It is available here.

https://github.com/synthecypher/full-preload

Question

I noticed that when I create a <video> element with sources and call load() , it will load up to about 36%, and then stops if you don't play() , and at that time it will continue to load the rest of the video, which he plays.

However, I want the entire video to be downloaded before it was an element in the timed exercise, and if the Internet connection drops during the exercise, I will have to detect such an event and restart the exercise.

I suppose this is an inline function of HTML5 multimedia elements, but is it possible to override this native functionality?

I tried to load the entire video source as arraybuffer using XMLHttpRequest , which is then converted to blob and set as src of the <source> element in my <video> element.

This does work, but it is not ideal, because I cannot report the progress of the download to the user using the progress bar, since XHR is a synchronous operation and will cause my JavaScript to freeze until an answer is received. I know that XHR2 now has this functionality, but I need to support IE8 + so that is not an option.

Is there a lighter, more elegant solution to my problem that reports progress?

Requirements

  • Before playback, you must first download the entire <video> <source> element.
  • Need to report progress
+5
source share
2 answers

If you have a source, you can preload the data into blob in javascript and play when you are ready.

The following should work if the video is on your server. If not, you will run into CORS issues.

 var video = document.getElementById("Your video element id") var url = "Some video url" var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.responseType = "arraybuffer"; xhr.onload = function(oEvent) { var blob = new Blob([oEvent.target.response], {type: "video/yourvideosmimmetype"}); video.src = URL.createObjectURL(blob); //video.play() if you want it to play on load }; xhr.onprogress = function(oEvent){ if(oEvent.lengthComputable) { var percentComplete = oEvent.loaded/oEvent.total; // do something with this } } xhr.send(); 
+6
source

Here is an example to preload the full video using XHR. but you need to handle CORS yourself.

 var xhrReq = new XMLHttpRequest(); xhrReq.open('GET', 'yourVideoSrc', true); xhrReq.responseType = 'blob'; xhrReq.onload = function() { if (this.status === 200) { var vid = URL.createObjectURL(this.response); video.src = vid; } } xhrReq.onerror = function() { console.log('err' ,arguments); } xhrReq.onprogress = function(e){ if(e.lengthComputable) { var percentComplete = ((e.loaded/e.total)*100|0) + '%'; console.log('progress: ', percentComplete); } } xhrReq.send(); 
+2
source

Source: https://habr.com/ru/post/1214593/


All Articles