Paul Ledger
Paul Ledger

Reputation: 1135

Video validation client side how to get the duration of the video

I have program that allows the user to choose a file and get the exact length of the video file. The code I have gets the length but as soon as i try to output this in any way it is outputted as Nan or undefined. Is there a reason why?

Jquery

$('#auto_select_vid').click( function () {
    $('#select_video').click();
});
$('#select_video').on('change', function (event) {
    var file = event.currentTarget.files[0]; 
    var objectUrl = URL.createObjectURL(file); 
    $('#test_video_player').prop('src',objectUrl);
    var seconds = $("#test_video_player")[0].duration;
    console.log($("#test_video_player")[0].duration);
    console.log($("#test_video_player"));
});

HTML:

<div id="auto_select_vid" class="button">Detect Video Info</div>
<input type="file" id="select_video" style="display:none;" />
<video id="test_video_player" style="display:none;"></video>

The Function function example

The user clicks the button and selects a video file. Everthing triggers but in the console log it displays undefined for

console.log($("#test_video_player")[0].duration);

But when on the second console log the duration can clearly be seen. If this cant be done is there a php method I can use to send the duration back with JSON?

Upvotes: 3

Views: 1520

Answers (1)

Alessio Cantarella
Alessio Cantarella

Reputation: 5201

Before accessing video metadata, you have to be sure they have been loaded:

var video = document.getElementById("test_video_player");
video.onloadedmetadata = function() {
    // do your stuff with duration, etc.
};

Upvotes: 2

Related Questions