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

I'm experiencing difficulties in installing dependencies for my project through npm, as it keeps showing an error

Recently, I decided to delve into the world of HTML5 and javascript games by running a browser game from Github. The game that caught my eye is called BrowserQuest, and you can find it on Github. A hiccup arose while using npm debug: 237 error 404 Not ...

Automating the movement of a slider input gradually throughout a specified duration

I am working on a website that includes a range input setup like this: <input type="range" min="1036000000000" max="1510462800000" value="0" class="slider" id ="slider"/> Additionally, I have integrated some D3 code for visualizations. You can view ...

TypeScript async function that returns a Promise using jQuery

Currently, I am facing a challenge in building an MVC controller in TypeScript as I am struggling to make my async method return a deferred promise. Here is the signature of my function: static async GetMatches(input: string, loc?: LatLng):JQueryPromise& ...

What could be causing the CastError: Cast to ObjectId failed in my code?

Whenever I try to access a specific route in my project, the following error is returned: Server running on PORT: 7000 /user/new CastError: Cast to ObjectId failed for value "favicon.ico" (type string) at path "_id" for model "User" at model.Query.exe ...

Share your message with BotFramework WebChat by simply clicking on the provided link

A chatbot I created using Microsoft Bot Framework has been integrated into my website through DirectLine: <div id="chatbot_body"></div> <script src="https://unpkg.com/botframework-webchat/botchat.js"></script> <script> ...

JS problem with decreasing

Within a React component, I have implemented the following method: addWidget = (index) => { let endX = this.state.widgets.reduce((endX, w) => endX.w + w.w, 0) console.log(endX); if (endX === 12) endX = 0 this.setState({ wi ...

How to transfer the application version from package.json to a different non-JSON file in Angular and node.js

While developing my Angular application, I encountered a task where I needed to extract the version number from the package.json file and transfer it to a non-json file. The content of my package.json file is as follows: { "name": "my app ...

Tips on creating a slow and gradual border animation that unfolds smoothly

I am looking to create an animation effect on a border, gradually revealing it like in this Codepen example. However, my specific requirements are: The previous line should not be removed, but rather shown along with the new border. The border color ...

Is there a way for me to assign values to my array within each loop when the inner elements vary?

Every time I work on this JavaScript code, I feel like I'm close to finishing it but then encounter another obstacle. My goal is to extract values from different elements such as <input type="text"> and <select>. Here's the code snipp ...

The Javascript function will only initiate upon a manual reload of the page

My function is working perfectly, but only after I reload the page once it has been loaded. This function is a timer that starts counting down from 10 to 0 as soon as the page loads (which is the intended behavior). However, when I first land on the page ...

Ways to retrieve a JSON element and incorporate it into a CSS styling

Can someone assist me in converting a JSON object for use in CSS? I've attempted to do this using Vue.js, creating a map legend with v-for to generate the legend. However, if there is an alternative method that allows me to take a JSON object and ins ...

Converting numbers in React Native, leaving only the last four digits untouched

When mapping biomatricData.ninId, the value I am receiving is "43445567665". biomatricData.ninId = 43445567665 My task now is to display only the last 4 digits and replace the rest with "*". I need to format 43445567665 as follows: Like - *******7665 ...

Game Mapping Techniques: Utilizing Spatial Data Structures

In order to efficiently store and retrieve intersecting rectangles, I am currently working on implementing a spatial data structure in JavaScript. My initial approach involves using a Quad Tree to narrow down the search space. However, for dynamic objects ...

Utilize jQuery and HTML simplistically to display or conceal divs throughout a webpage

After developing some basic jQuery code using if-statements to toggle the visibility of Divs based on a select list in HTML, I am seeking ways to enhance this code: 1) How can I achieve the same functionality with fewer lines of code? 2) Rather than manu ...

ag-grid Server Side pagination function to enable independent setting of last row

Currently, I am utilizing ag-grid, Angular 7, and implementing a server-side datasource with pagination. In my API setup, I initiate two requests: the first request provides the total number of items in the table, while the second fetches the data for the ...

Unable to Retrieve JSON Output

PHP Code: $contents = ''; $dataarray = file('/location/'.$_GET['playlist'].''); //Loading file data into array $finallist = ''; //Extract Track Info foreach ($dataarray as $line_num => $line) //Loopin ...

The webpage displays the element as <span class="icon">&#xe80d;</span> instead of rendering it properly

In my ReactJS project, I have created a component called Menu1item: class Menu1item extends React.Component{ render(){ return ( <div> {this.props.glyph}{this.props.value} </div> ) ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

Personalizing the pop-up window using window.open

When clicking a hyperlink on a page, I need to open multiple pop-up windows. To achieve this, I must use the Window.open function instead of showModalDialog. However, I have noticed that the appearance is not satisfactory when using Window.open. (Essentia ...

"Unraveling Vue.js: A guide to fetching JSON data one object at a time

I am facing a challenge with a large JSON file (40 MB) that includes data on countries, their IDs, and a total sum that I need to calculate. { "0": { "id": 0, "country": "usa", "sum": 201, }, ...