skip to Main Content

Greatly confused with the seemingly conflicting info out there.

I am trying to cobble together a bare-bones select file and play video player (for later streaming to a NodeJs server).

I am having great trouble getting the browser to playthe selected video.

The code is here:

<script>

function newVideo ()
{
  const mediaStream = new MediaStream();
  const url = URL.createObjectURL(mediaStream);
  var vplayer = document.getElementById('vplayer');
  var vfile = document.getElementById('videoFile');
  console.log(' vfile: ', vfile.files[0].name);
  source.src = mediaStream;
//  source.src = URL.createObjectURL(vfile.files[0].name);
//  source.parent().load();
}

</script>

<video width="400" controls>
  <source src="" id="vplayer">
    Your browser does not support HTML5 video.
</video>

<input type="file" name="file[]" id="videoFile"
       class="file_multi_video"
       onchange='newVideo();'
       accept="video/*">

When I run this, selecting a MP$ video file, I get the error:

Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.
    at newVideo (video.html:7:19)
    at HTMLInputElement.onchange (video.html:23:114)

2

Answers


  1. To fix the error you can create a Blob from the selected file
    thing like this …

    function newVideo() {
      const vplayer = document.getElementById('vplayer');
      const vfile = document.getElementById('videoFile');
      const file = vfile.files[0];
      
      if (file.type.indexOf('video') === -1) {
        console.log('صيغة الملف غير مدعومة');
        return;
      }
      
      const reader = new FileReader();
      reader.onload = function() {
        const blob = new Blob([new Uint8Array(reader.result)]);
        const url = URL.createObjectURL(blob);
        vplayer.src = url;
        vplayer.play();
      };
      reader.readAsArrayBuffer(file);
    }
    
    
    Login or Signup to reply.
  2. You should create the URL for the <source> element using the file set in the input.

    function newVideo ()
    {
      var vplayer = document.getElementById('vplayer');
      var vfile = document.getElementById('videoFile');
      console.log(' vfile: ', vfile.files[0].name);
      var source = document.createElement('source')
      source.src = URL.createObjectURL(vfile.files[0]);
      vplayer.replaceChildren(source);
    }
    <video id="vplayer" width="400" controls></video>
    
    <input type="file" name="file[]" id="videoFile"
           class="file_multi_video"
           onchange='newVideo();'
           accept="video/*">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search