如何从html中的输入字段播放视频

con*_*449 6 html variables video

我想创建一个页面,允许用户从本地计算机选择视频文件,然后在 html 上播放该视频。我已经弄清楚了每个单独的部分,但如何让它们进行交互。

为了获取用户输入,我有这个:

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

<input type="file"
       id="input" name="input_video"
       accept="video/mp4, video/mov">
Run Code Online (Sandbox Code Playgroud)

要播放视频,我有这个:

<video width="320" height="240" controls>
  <source src="" type="video/mp4">
</video>
Run Code Online (Sandbox Code Playgroud)

如何获取从用户输入文件路径收集的任何值作为变量以供第二段代码播放?

谢谢。

编辑

我的代码现在看起来像这样,但视频文件播放器不会播放我选择的文件。

<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>

Run Code Online (Sandbox Code Playgroud)

aja*_*row 9

使用 javascript 中的输入change事件来获取文件,然后用于URL.createObjectURL创建一个临时文件以用作 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();
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

编辑

只需删除源元素并将媒体直接添加到视频元素即可触发播放。