Mike
Mike

Reputation: 552

Change Video source to blob / ObjectURL

I would like to hide a video source's attribute. Therefore I wanted to convert the src attribute of the video's source-tag into an objectURL. It sadly doesn't work.

I already tried

function display(vid){
    var video = document.getElementById("video");
    video.src = window.URL.createObjectURL(vid);
}

display('video.mp4');

(as provided here: Display a video from a Blob Javascript)

That did not work and the Stack is already 5 years old.

HTML Looks like this

<video id="video">
   <source type="video/mp4" src="video.mp4">
</video>

Upvotes: 1

Views: 6443

Answers (2)

jmsn
jmsn

Reputation: 1080

Change the src attribute at the video element directly to the new blob URL.


An example that worked for me:

HTML:

<video width="320" height="240" controls></video>

JS:

function changeVideoSource(blob, videoElement) {
  var blobUrl = URL.createObjectURL(blob);
  console.log(`Changing video source to blob URL "${blobUrl}"`)
  videoElement.src = blobUrl;
  videoElement.play();
}

function fetchVideo(url) {
  return fetch(url).then(function(response) {        
    return response.blob();
  });
}

fetchVideo('https://wherever.com/video.mp4').then(function(blob) {
  changeVideoSource(blob, video);
});

Upvotes: 8

Mike
Mike

Reputation: 552

Current code looks like this

function blobClip(obj){
   var video = obj;
   var sources = video.getElementsByTagName('source');
   var newReq = new Request(sources[0].src);
   fetch(newReq)
   .then(function(response) {        
        return response.blob();
   })
   .then(function(myBlob) {
        var objectURL = URL.createObjectURL(myBlob);
        sources[0].src = objectURL;
   });
}

That did not really work. I also tried adding video.load() after the source[0].src got its new objectURL.

Im pretty sure the function call maybe wrong: I added onloadeddata="blobClip(this);" to the video tag. I also tried onload with no success.

Upvotes: 1

Related Questions