connor449
connor449

Reputation: 1679

How to play video from input field in html

I want create a page that allows a user to choose a video file from their local machine, and then have that video play on html. I have each separate portion figured out, but how do I get them to interact.

To get user input I have this:

<label for="input">Choose a video file to process:</label>

<input type="file"
       id="input" name="input_video"
       accept="video/mp4, video/mov">

and to play a video I have this:

<video width="320" height="240" controls>
  <source src="" type="video/mp4">
</video>

How do I get whatever value is collected from the user input file path as a variable to be what is played by the second piece of code?

Thanks.

edit

My code now looks like this, but the video file player will not play the file I select.

<label for="input">Choose a video file to process:</label>


<script>document.getElementById("input").addEventListener("change", function() {
  var media = URL.createObjectURL(this.files[0]);
  var video = document.getElementById("video");
  video.src = media;
  video.style.display = "block";
  video.play();
});
</script>

<label for="input">Choose a video file to process:</label>
<input type="file" id="input" name="input_video" accept="video/mp4, video/mov">
<video id="video" width="320" height="240" controls style="display"></video>

Upvotes: 6

Views: 6735

Answers (2)

Another way to do it es replacing the html of the video tag

html:

<video id="vp" autoplay muted loop controls>
    <source id="videoprev" src=""  type="video/mp4">
</video>

JQuery:

$("#vp").html('<source src="'+URL.createObjectURL(file)+'" type="video/mp4"></source>');

In this case we take the src from an input file

Upvotes: 0

ajarrow
ajarrow

Reputation: 484

Use the input's change event in javascript to get the file and then use URL.createObjectURL to create a temorary file to use as a src.

document.getElementById("input").addEventListener("change", function() {
  var media = URL.createObjectURL(this.files[0]);
  var video = document.getElementById("video");
  video.src = media;
  video.style.display = "block";
  video.play();
});
<label for="input">Choose a video file to process:</label>
<input type="file" id="input" name="input_video" accept="video/mp4, video/mov">
<video id="video" width="320" height="240" controls style="display: none;"></video>

EDIT

Just remove the source element and add the media directly to the video element and then trigger the playing.

Upvotes: 11

Related Questions