Javascript 输入视频文件时获取视频时长

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29285056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:05:25  来源:igfitidea点击:

Get video duration when input a video file

javascripthtml

提问by davis

I'm doing a project with HTML and Javascript that will run local with local files. I need to select a file by input, get it information and then decide if I'll add to my list and reproduce or not. And if i decide to use it I'll have to put it on a queue to use later. Otherwise I'll just discard and select another file.

我正在使用 HTML 和 Javascript 做一个项目,该项目将使用本地文件在本地运行。我需要通过输入选择一个文件,获取它的信息,然后决定是否将其添加到我的列表中并进行复制。如果我决定使用它,我将不得不将它放在队列中以备后用。否则,我将丢弃并选择另一个文件。

The problem that I'm facing is that I cant't find a way to get the vídeo duration just by selecting it on input.

我面临的问题是我无法找到一种方法来仅通过在输入时选择它来获得视频持续时间。

I've searched a lot and I didn't find any method to get the duration. In this code below I tried to use 'file.duration' but didn't work, it just returns 'undefined'.

我搜索了很多,但没有找到任何获取持续时间的方法。在下面的这段代码中,我尝试使用“ file.duration”但没有用,它只返回“ undefined”。

That's my input, normal as you can see.

这是我的输入,如您所见,很正常。

<div id="input-upload-file" class="box-shadow">
   <span>upload! (?????)</span> <!--ignore the text face lol -->
   <input type="file" class="upload" id="fileUp" name="fileUpload" onchange="setFileInfo()">
</div>

And that's the function that I'm using to get all the information.

这就是我用来获取所有信息的功能。

function setFileInfo(){
  showInfo(); //change div content
  var file = document.getElementById("fileUp").files[0];
  var pid =  1;
  var Pname = file.name;
  Pname = Pname.slice(0, Pname.indexOf(".")); //get filename without extension
  var Ptype = file.type;
  var Psize = bytesToSize(file.size); //turns into KB,MB, etc...
  var Pprior = setPriority(Ptype); //returns 1, 2 or 3 
  var Pdur = file.duration;
  var Pmem = getMemory(Psize); //returns size * (100 || 10 || 1)
  var Pown = 'user';
  /* a lot of stuff throwing this info to the HTML */
  console.log(Pdur);
}

Is there way to do this? If not, what are the alternatives that can help me?

有没有办法做到这一点?如果没有,有哪些替代方案可以帮助我?

回答by Kaiido

In modern browsers, You can use the URL API's URL.createObjectURL()with an non appended video element to load the content of your file.

现代浏览器中,您可以使用URL.createObjectURL()带有非附加视频元素的 URL API来加载文件的内容。

var myVideos = [];

window.URL = window.URL || window.webkitURL;

document.getElementById('fileUp').onchange = setFileInfo;

function setFileInfo() {
  var files = this.files;
  myVideos.push(files[0]);
  var video = document.createElement('video');
  video.preload = 'metadata';

  video.onloadedmetadata = function() {
    window.URL.revokeObjectURL(video.src);
    var duration = video.duration;
    myVideos[myVideos.length - 1].duration = duration;
    updateInfos();
  }

  video.src = URL.createObjectURL(files[0]);;
}


function updateInfos() {
  var infos = document.getElementById('infos');
  infos.textContent = "";
  for (var i = 0; i < myVideos.length; i++) {
    infos.textContent += myVideos[i].name + " duration: " + myVideos[i].duration + '\n';
  }
}
<div id="input-upload-file" class="box-shadow">
  <span>upload! (?????)</span>
  <input type="file" class="upload" id="fileUp" name="fileUpload">
</div>
<pre id="infos"></pre>

回答by ricks

I needed to validate a single file before continuing to execute more code, here is my method with the help of Kaiido's answer!

我需要在继续执行更多代码之前验证单个文件,这是我在 Kaiido 的回答的帮助下的方法!

onchange event when a user uploads a file:

用户上传文件时的 onchange 事件:

$("input[type=file]").on("change", function(e) {

    var file = this.files[0]; // Get uploaded file

    validateFile(file) // Validate Duration

    e.target.value = ''; // Clear value to allow new uploads
})

Now validate duration:

现在验证持续时间:

function validateFile(file) {

    var video = document.createElement('video');
    video.preload = 'metadata';

    video.onloadedmetadata = function() {

        window.URL.revokeObjectURL(video.src);

        if (video.duration < 1) {

            console.log("Invalid Video! video is less than 1 second");
            return;
        }

        methodToCallIfValid();
    }

    video.src = URL.createObjectURL(file);
}