What is the method to determine the duration of a video using the FileReader function to access the video file?

My current challenge involves uploading a video to a server and reading it on the client end using `readAsBinaryString()` from FileReader.

However, I am facing an issue when trying to determine the duration of this video file.

If I attempt to read the file and set the reader's data as the source for a video tag, none of the events related to the video tag are triggered. It is crucial for me to find the duration of the uploaded file on the client side.

Could someone kindly provide me with suggestions on how to overcome this obstacle?

Answer №1

If you want that to be functional, consider the following approach:

  • Begin by reading the file as an ArrayBuffer (this can later be sent directly to the server as a binary stream)
  • Package it within a Blob object
  • Create a URL for the blob object
  • Set the URL as the video source

Once the video object triggers the loadedmetadata event, you will be able to retrieve the duration.

Alternatively, you could utilize data-uri, although keep in mind that browsers might impose size restrictions and other limitations, especially crucial for video files. Additionally, there is a notable encoding/decoding overhead from the Base-64 process.

For instance...

Select a video file compatible with the browser (in practical scenarios, filter allowed file types based on video.canPlayType()).

The duration will display once the aforementioned steps are completed (the example lacks error handling, so adjust accordingly).

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

  var file = e.target.files[0],                               // chosen file
      mime = file.type,                                       // save MIME type
      rd = new FileReader();                                  // instantiate a FileReader
  
  rd.onload = function(e) {                                   // when file is read:
    
    var blob = new Blob([e.target.result], {type: mime}),     // create a blob of buffer
        url = (URL || webkitURL).createObjectURL(blob),       // generate o-URL for blob
        video = document.createElement("video");              // initialize video element

    video.preload = "metadata";                               // preload setting
    video.addEventListener("loadedmetadata", function() {     // upon meeting data load requirements
      document.querySelector("div")
          .innerHTML ="Duration: "+ video.duration + "s";   // show duration
      (URL || webkitURL).revokeObjectURL(url);                // cleanup

      // ... continue from here ...

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

Answer №2

If you want to achieve something similar, you can follow the example below, where the key is to utilize the readAsDataURL method:

var fileReader = new FileReader();
fileReader.onload = function() {
    var multimedia = new Audio(fileReader.result);
    multimedia.onloadedmetadata = function(){
         multimedia.duration; // You can obtain the duration of the video/audio file here
    };    
};
fileReader.readAsDataURL(file); 

Check out the Fiddle Demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

HTML5 input type Color displays individual RGB values

This code snippet opens up a variety of options for the user to manipulate different color values such as R, G, B, HEX VALUE, HUE, etc. However, the specific requirement is to only extract the Red value. <input id="color_pick"type="color" value="#ff0 ...

Understanding the process of parsing JSON response using JavaScript

I am facing an issue with reading a JSON object in JavaScript. I have received this JSON object as a response and now I need to create a jstree based on it. Here is my JavaScript code: var repoId = $('#frmHdnV').val(); // variable to hold req ...

How can one save a text value element from a cascading list in ASP.NET MVC?

I have recently started learning about javascript, jquery, and ajax. In my model, I have defined the following classes: namespace hiophop.Models { public class CarMake { public class Category { public int CategoryID { g ...

Symfony: The Database Query Button with a Pop-up Feature

I am looking to create a button that will automatically search my database for all users with a "secouriste" attribute set and display their first name, last name, and phone number in a popup. After conducting research, here is what I have gathered: In m ...

I seem to be missing something, as the client_id is required for Next Auth. What could it

I seem to be facing some confusion with where the communication breakdown is occurring. [...nextauth].js import NextAuth from "next-auth" import GoogleProvider from "next-auth/providers/google" export default NextAuth({ provider ...

Issues with javascript functionality in Internet Explorer version 9 and higher

Currently, there is a flash music player (audioplay) embedded on a website. Despite personal preferences against having music on websites, it was requested by the client. The functionality in question involves using JavaScript to trigger "stop" and "play," ...

Changing from a vertical to horizontal menu as the parent div is resized

I am looking for a solution to create a CSS effect or Javascript code that will hide a menu inside a div when the browser window or parent div is resized. I want to display another div with the same menu in horizontal orientation when the first one is hidd ...

Utilizing Javascript to maintain an ongoing sum within a <span> tag

I'm working on a code snippet to create a running total feature. Essentially, every time a user clicks a button to add the subtotal to the total, I want it to keep accumulating in the running total. Currently, the setup involves a dropdown menu with t ...

Prevent the ability to add options dynamically to a drop-down select list

I have implemented a dynamic data retrieval feature from my database using jQuery's .getJSON function and appended the data to an HTML select drop-down list. The JavaScript code for this functionality is as follows: $.getJSON('url', f ...

Analyzing the structure according to the month/week/year

My array consists of count and date values: day = [ { count: 1, date: '2022-07-07' }, { count: 1, date: '2022-08-14' }, { count: 2, date: '2022-07-19' }, { count: 4, date: '2022-07-19' }, { count: 2, date: ...

Sorry, the server cannot be reached at the moment. Please try again later

Recently delving into Node.js and just getting started on using MongoDB. Currently establishing a connection with my MongoDB Cluster that I have set up. const dbURI = 'mongodb+srv://testuser:<a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

The custom validation process encountered an error: callback is not a valid function

Encountering an issue with a custom validator in node.js while using mongoose. The goal is to verify if a query already exists in the headerLog before attempting to insert it. Take a look at the code snippet below: var mongoose = require('mongoose& ...

Is there a way to display these panels in a scrollable table layout?

My aim is to replicate this specific styling: https://i.stack.imgur.com/jz5lm.png This type of table shown above is being dynamically imported via Redux: class LocationList extends React.Component { componentDidMount() { this.props.fetchLocations( ...

Validating Angular UI Route state with Protractor

I've been experimenting with the protractor framework to conduct tests on my angular application. Is it possible for me to verify the angular state during an end-to-end test? ...

The successful Ajax POST request does not result in an update to the JSON file

I am facing an issue with adding data to a *.JSON file. Despite receiving a "success" message from Ajax, the file remains unchanged. I have also noticed that when the JSON file is empty, nothing happens at all. Can someone help me find a solution? I'm ...

How can I stop popup labels from appearing in MapBox GL JS when I don't want them to be visible?

Having created an application using MapBox GL JS, I have placed numerous markers all around the globe. As the mouse hovers over these markers, a description box pops up, which is what I intended. However, I am encountering an issue where these labels flick ...

Key within square brackets in a JSON array

I am dealing with a JSON array that includes a square bracket in the key, like this: { "msg":"OK", "data":[ { "nls!type":"NCR", "current":"Assign", "physicalid":"0FFE0001000009FC5BD6805C00001352", "attribute[custTitle]":"Tit ...

What causes an error when trying to access with the member access operator?

When dealing with object properties in the code snippet below, an error is thrown when trying to access the object using the Member Access. Why does this happen? var d = {a: 10, b: 20, c:30}; var keys = Object.getOwnPropertyNames(d); ...

Using Javascript within AEM to update a class upon checkbox selection

I need assistance targeting the 'horizontal-video' class within a div in an AEM component. I am attempting to add a second class called 'flipped' to the div if the author clicks on a checkbox with the ID of 'coral-id-540'. Unf ...

The issue arises when I try to retrieve information from MySQL using Ajax, as it appears

I am currently working on developing an ecommerce website. In order to display products, I am fetching data from a database. My goal is to allow users to add products to their cart without having to refresh the page. I have attempted to use AJAX for this ...