Get video duration after uploading

After uploading a file, Uploadcare Widget allows you to get file information provided by the Upload API. The fileinfo object contains various fields such as file name, size, type, image information, etc. However, if the file is a video, its fileinfo object won’t contain its duration and other video-specific information.

Sometimes, it’s crucial to have the duration of the media file once it has been uploaded. For example, if your app requires videos not to be longer than N seconds, and to ensure this, it trims too long videos with our Video processing API.

In this case, video duration can be obtained with some JavaScript. To do so, you need to get the file object, create an object URL out of it, create a hidden HTML video element, and set its src to the object URL generated. After that, the video length will be available through the duration property of the video element.

// get the widget object
const widget = uploadcare.Widget('[role=uploadcare-uploader]');
// regexp to check if the file is audio/video
const regexp = /^(audio|video)\//gi;
// wait until a file is uploaded and get it's info
widget.onUploadComplete(fileInfo => {
  if (regexp.test(fileInfo.mimeType)) {
    // get the file object
    const fileObject = fileInfo.sourceInfo.file;
    // create a URL from the file object
    const url = URL.createObjectURL(fileObject);
    // create a hidden video element 
    const video = document.createElement('video');
    // set the file object URL as the src of the video element
    video.src = url;
    // get video/audio duration when it's available
    video.addEventListener('loadedmetadata', () => {
      console.log(`Duration: ${video.duration.toFixed(2)}s`);
    });
  }
  // any additional post-uploading logic can go here
});

This technique works for audio files as well. You can play around with a live demo here.