0

I have a function that logs the video duration into the console before the video is uploaded. However, I cannot get the video duration outside the addEventListener function because it returns back NaN. Despite of it, inside the function it successfully logs the proper video duration but if I save it into a variable it does not get the right value.

Video duration function

var duration = 0; // Set default variable for storing video duration
if(vfile.type == "video/webm" || vfile.type == "video/mp4" || vfile.type == "video/ogg" || vfile.type == "video/mov"){
        var video = document.createElement('video'); // Create video element
        video.preload = 'metadata'; // Set preload attribute to metadata
        window.URL.revokeObjectURL(video.src);
        video.addEventListener('durationchange', function() { // Check for duration
            console.log('Duration change', video.duration); // Successfully logs video duration into console e.g.: 13.012
            duration = video.duration; // Set duration variable to video.duration
        });
        console.log("Duration: ", duration); // Returns back 0
    }
    video.src = URL.createObjectURL(vfile);

If I set variable duration to video.duration outside the addEventListener function it gives back NaN.
All in all, how could I set variable duration to the actual video duration for later usage in the script?

squancy
  • 565
  • 1
  • 7
  • 25
  • Possible duplicate of: https://stackoverflow.com/questions/19592009/html5-video-duration-without-playing-video – Steve Jun 06 '18 at 14:02
  • Some other issues unrelated to your question: you're setting `video.src` outside of the block of code that creates the video element. Also `revokeObjectURL` runs before `video.src` is set (and before the video is loaded), so it is effectively doing nothing. – Steve Jun 06 '18 at 14:35

1 Answers1

2

You are assigning video.duration to duration in this code:

    video.addEventListener('durationchange', function() { // Check for duration
        console.log('Duration change', video.duration); // Successfully logs video duration into console e.g.: 13.012
        duration = video.duration; // Set duration variable to video.duration
    });
    console.log("Duration: ", duration); // Returns back 0

The problem is that console.log("Duration: ", duration); runs before duration = video.duration;, because video.addEventListener does not immediately run its function. If you do need to do something with the duration, you can run it after you assign the duration, like so:

    video.addEventListener('durationchange', function() { // Check for duration
        duration = video.duration; // Set duration variable to video.duration
        someOtherFunction();
    });

You could also use one of the other asynchronous data management techniques: https://stackoverflow.com/a/14220323/6184972

Steve
  • 10,435
  • 15
  • 21