Get Video Duration When Input a Video File

Get video duration when input a video file

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.

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>

Is there any way we can get video duration before upload?

Try this

<form action="#" method="post" enctype="multipart/form-data">  File: <input type="file" name="fup" id="fup" /><br>  Duration: <input type="text" name="f_du" id="f_du" size="5" /> seconds<br>  <input type="submit" value="Upload" /></form><audio id="audio"></audio>
<script>// Code to get duration of audio /video file before upload - from: http://coursesweb.net/
//register canplaythrough event to #audio element to can get durationvar f_duration =0; //store durationdocument.getElementById('audio').addEventListener('canplaythrough', function(e){ //add duration in the input field #f_du f_duration = Math.round(e.currentTarget.duration); document.getElementById('f_du').value = f_duration; URL.revokeObjectURL(obUrl);});
//when select a file, create an ObjectURL with the file and add it in the #audio elementvar obUrl;document.getElementById('fup').addEventListener('change', function(e){ var file = e.currentTarget.files[0]; //check file extension for audio/video type if(file.name.match(/\.(avi|mp3|mp4|mpeg|ogg)$/i)){ obUrl = URL.createObjectURL(file); document.getElementById('audio').setAttribute('src', obUrl); }});</script>

how to get duration of multiple video while uploading?

You need to "load" the file into a video node and wait for the meta data of the file to be loaded and extract the duration from the loaded node. Here is a function to get the duration from a file. Note that this function returns a promise:

function getDuration(file) {
let videoNode = document.createElement("video");
let promise = new Promise(function(resolve, reject) {
videoNode.addEventListener("loadedmetadata", function() {
resolve(videoNode.duration);
});
videoNode.addEventListener("error", function() {
reject(videoNode.error.message + "(" + videoNode.error.code + ")");
});
});

const URL = window.URL || window.webkitURL;
videoNode.src = URL.createObjectURL(file);

return promise;
}

You can then call this function like this:

getDuration(file).then((duration) => {
// duration in seconds (as float)
});

Note! You need to reimplement your loop to wait for the promise to finish before you concatenate the txt variable and output it.

How I can know audio/video duration before uploading?

You can get the audio duration with HTMLMediaElement.duration:

async function getDuration(file) {
const url = URL.createObjectURL(file);

return new Promise((resolve) => {
const audio = document.createElement("audio");
audio.muted = true;
const source = document.createElement("source");
source.src = url; //--> blob URL
audio.preload= "metadata";
audio.appendChild(source);
audio.onloadedmetadata = function(){
resolve(audio.duration)
};
});
}

Then in your function:

const uploadFile = async (event) => {
let file = event.target.files[0];
//here api POST request where i should pass duration
const duration = await getDuration(file);
}:

How to Check Length / Duration of an Uploaded Video in JavaScript

How about something like this?

// create the video element but don't add it to the pagevar vid = document.createElement('video');document.querySelector('#input').addEventListener('change', function() {  // create url to use as the src of the video  var fileURL = URL.createObjectURL(this.files[0]);  vid.src = fileURL;  // wait for duration to change from NaN to the actual duration  vid.ondurationchange = function() {    alert(this.duration);  };});
<input type="file" id="input">

Check video length on upload - Angular

I'd add an invisible video player and set its source then get the duration from that:

HTML:

<input type="file" (change)="readVideoUrl($event)">

<p *ngIf="videoSizeError">Too big</p>

<video #video style="display: none;" *ngIf="videoUrl" width="320" height="240" controls [attr.src]="videoUrl" (loadedmetadata)="getDuration($event)">
</video>

TS:

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
videoUrl;
videoSizeError;

constructor(private sanitizer: DomSanitizer) { }

readVideoUrl(event: any) {
const files = event.target.files;
if (files && files[0]) {
this.videoUrl = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(files[0]));
}
}

getDuration(e) {
const duration = e.target.duration;
this.videoSizeError = duration > 30;
}
}

working code's link

How to get duration of video when I am using filereader to read the video file?

You can do something like this for that to work:

  • read the file as ArrayBuffer (this can be posted directly to server as a binary stream later)
  • wrap it in a Blob object
  • create an object URL for the blob
  • and finally set the url as the video source.

When the video object triggers the loadedmetadata event you should be able to read the duration.

You could use data-uri too, but notice that browsers may apply size limits (as well as other disadvantages) for them which is essential when it comes to video files, and there is a significant encoding/decoding overhead due to the Base-64 process.

Example

Select a video file you know the browser can handle (in production you should of course filter accepted file types based on video.canPlayType()).

The duration will show after the above steps has performed (no error handling included in the example, adjust as needed).

var fileEl = document.querySelector("input");
fileEl.onchange = function(e) {

var file = e.target.files[0], // selected file
mime = file.type, // store mime for later
rd = new FileReader(); // create a FileReader

rd.onload = function(e) { // when file has read:

var blob = new Blob([e.target.result], {type: mime}), // create a blob of buffer
url = (URL || webkitURL).createObjectURL(blob), // create o-URL of blob
video = document.createElement("video"); // create video element

video.preload = "metadata"; // preload setting
video.addEventListener("loadedmetadata", function() { // when enough data loads
document.querySelector("div")
.innerHTML = "Duration: " + video.duration + "s"; // show duration
(URL || webkitURL).revokeObjectURL(url); // clean up

// ... continue from here ...

});
video.src = url; // start video load
};
rd.readAsArrayBuffer(file); // read file object
};
<input type="file"><br><div></div>

Retrieving HTML5 video duration separately from the file

The issue is in WebKit browsers; the video metadata is loaded after the video so is not available when the JS runs. You need to query the readyState attribute; this has a series of values from 0 to 4, letting you know what state the video is in; when the metadata has loaded you'll get a value of 1.

So you need to do something like:

window.setInterval(function(t){
if (video.readyState > 0) {
var duration = $('#duration').get(0);
var vid_duration = Math.round(video.duration);
duration.firstChild.nodeValue = vid_duration;
clearInterval(t);
}
},500);

I haven't tested that code, but it (or something like it) should work.

There's more information about media element attributes on developer.mozilla.org.



Related Topics



Leave a reply



Submit