Receive video duration when entering a video file

I am doing a project with HTML and Javascript that will work locally with local files. I need to select a file using input, get its information, and then decide whether I will add to my list and play it or not. And if I decide to use it, I will have to queue it to use it later. Otherwise, I just drop it and select another file.

The problem I am facing is that I can’t find a way to get the duration of the vídeo by simply selecting it at the input.

I searched a lot and I did not find any way to get the duration. In this code below, I tried to use "file.duration", but did not work, it just returns "undefined".

This is 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 what a function that I use 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 any way to do this? If not, what alternatives can help me?

+5
source share
1 answer

In modern browsers , you can use the API URL URL.createObjectURL() with the added video element to load the contents of your file.

 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> 
+15
source

Source: https://habr.com/ru/post/1216211/


All Articles