javascriptmediastream

HTML5 Play Selected Video File


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)

Solution

  • 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/*">