如何让用户在他们的计算机上加载和播放 MP4 文件?

问题描述

我的 web 项目,使用 node.js / HTML / JavaScript,有一个视频播放器元素,我希望用户能够点击一个按钮在网页上播放 MP4 文件。我该怎么做?

这是我拥有的一些示例代码,其中包含视频元素,我可以让用户浏览他们的文件用户的视频文件必须上传到我的服务器吗?我希望他们只在浏览器中播放已经保存在计算机上的视频。

由于我的项目文件目录中已有其他视频,我执行 video.src = ... 在它们之间进行切换。所以我希望能想出一些类似的东西来播放用户自己的视频。

<input type="file" id="myFile" multiple size="50" onchange="myFunction()">

<p id="demo"></p>

<video id="video" playsinline style=" -moz-transform: scaleX(0);
            -o-transform: scaleX(0);
            -webkit-transform: scaleX(0);
            transform: scaleX(0);
            display: none;
            ">
            </video>
  
<script>
function myFunction(){
  var x = document.getElementById("myFile");
  var txt = "";
  if ('files' in x) {
    if (x.files.length == 0) {
      txt = "Select one or more files.";
    } else {
      for (var i = 0; i < x.files.length; i++) {
        txt += "<br><strong>" + (i+1) + ". file</strong><br>";
        var file = x.files[i];
        if ('name' in file) {
          txt += "name: " + file.name + "<br>";
        }
        if ('size' in file) {
          txt += "size: " + file.size + " bytes <br>";
        }
      }
    }
  } 
  else {
    if (x.value == "") {
      txt += "Select one or more files.";
    } else {
      txt += "The files property is not supported by your browser!";
      txt  += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property,it will return the path of the selected file instead. 
    }
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

最新尝试

这是我的处理程序中的相关代码,经过一些修改。它让我在单击输入元素后选择带有窗口弹出 gui 的文件,这很好。但是视频部分不起作用:

document.getElementById("upload_video").addEventListener("change",function() { 

    var file = this;
    console.log('Selected file: ' + file);
    var objectURL = URL.createObjectURL(file);
    //document.getElementById("video").src = objectURL;
    
    if (isVideo(file) == false) { //just checks extension name for e.g. .mp4,.avi,etc
        alert("Error - not a video file.");
        return;
    }
    
    video.src = objectURL;

});

选择有效的 mp4 文件时使用此代码出现的当前错误

(console.log) Selected file: [object HTMLInputElement]
Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution Failed.
    at HTMLInputElement.<anonymous>

我应该如何解决这个问题?

解决方法

无需将视频上传到任何地方。您仍然可以设置 video.src;要获取它的值,请使用 URL.createObjectURL method 并将文件传递给它。因此,假设您已经有一个特定的 file 变量(例如在您的 myFunction 中):

var objectURL = URL.createObjectURL(file);
document.getElementById("video").src = objectURL;

为了节省内存,尤其是视频,您应该在不再需要时(例如,选择另一个视频时)在 objectURL 上调用 URL.revokeObjectURL

,
<video width="400" controls>
  <source src="random.mp4" type="video/mp4">
  <source src="random.ogg" type="video/ogg">
  Your browser does not support HTML video.
</video>