Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

javascript - set video objects source file to a blob url

As an example, say I have a video object set on my website with the following attributes:

<video controls="" preload="auto" id="_video"></video>

and the original source being ./video/video.mp4 (for example).

How can I go about protecting the original source files location through converting it to a BLOB url?

I have seen a few posts stating that it needs to be done within through JavaScript, but none of them actually go to the extent of explaining how to do it, or where you can find out.

So, how would you do it; and what is the best way of doing it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Request the video using a new XMLHttpRequest() with the responseType set to blob.

Pass the xhr.result to a new FileReader() using readAsDataURL, which will give you a base-64 encoded string representation of the file.

Pass this string to atob to decode the base-64 encoded string to a string representing each byte of binary data. Now you can create an array of byte values using charCodeAt looping over the byte string.

This array can be passed to new Uint8Array() to create a typed array of 8-bit unsigned ints, which then can be passed to the new Blob() constructor.

Now that you have a blob you can use URL.createObjectURL() and pass the created blob to it. The created object url can be passed to the src attribute of your video DOM element.

Here is a quick and dirty example. Hope it helps. Make sure to go over the docs of all of the methods being used and check their browser support. This will not protect your video from being downloadable though.

var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';

xhr.onload = function() {
  
  var reader = new FileReader();
  
  reader.onloadend = function() {
  
    var byteCharacters = atob(reader.result.slice(reader.result.indexOf(',') + 1));
    
    var byteNumbers = new Array(byteCharacters.length);

    for (var i = 0; i < byteCharacters.length; i++) {
      
      byteNumbers[i] = byteCharacters.charCodeAt(i);
      
    }

    var byteArray = new Uint8Array(byteNumbers);
    var blob = new Blob([byteArray], {type: 'video/ogg'});
    var url = URL.createObjectURL(blob);
    
    document.getElementById('_video').src = url;
    
  }
  
  reader.readAsDataURL(xhr.response);
  
};

xhr.open('GET', 'https://upload.wikimedia.org/wikipedia/commons/c/c0/Roaring_Burps.ogg');
xhr.send();
<video controls="" preload="auto" id="_video"></video>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...