Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Audio duration NaN on certain page request action

I have been trying to create my custom media player using HTML5 and Jquery.

I have followed different approaches and ran into some trouble based on my way of refreshing the page.

First Case

$(document).ready(function(){
    duration = Math.ceil($('audio')[0].duration);
    $('#duration').html(duration);
});

In this case, the duration returns NaN when I redirect the page to the same URL by pressing the ENTER key in the address bar. However, it works completely fine when I refresh using the reload button or by pressing the F5 button.

Second Case

I read in some answers that loading duration after the loadedmetadataevent might help. So I tried the following:

$(document).ready(function(){
    $('audio').on('loadedmetadata', function(){
        duration = Math.ceil($('audio')[0].duration);
        $('#duration').html(duration);
    });
});

Surprisingly, in this case, the inverse of the first case happened. The duration gets displayed completely fine in the case of a redirect, i.e., pressing ENTER while in the address bar. However, in the case of refreshing using the F5 button or the reload button, the duration doesn't get displayed at all, not even NaN which led me to believe that the code doesn't get executed at all.


Further reading suggested this might be a bug within the webkit browsers but I couldn't find anything conclusive or helpful.

What could be the cause behind this peculiar behavior? It'd be great if you could explain it along with the solution to this problem.

Edit: I am mainly looking for an explanation behind this difference in behavior. I would like to understand the mechanism behind rendering a page in the case of redirect and refresh.

like image 798
Akshay Khetrapal Avatar asked Jun 11 '15 00:06

Akshay Khetrapal


1 Answers

It sounds like the problem is that the event handler is set too late, i.e. the audio file has loaded its metadata before the document is even ready.

Try setting the event handler as soon as possible by removing the $(document).ready call:

$('audio').on('loadedmetadata', function(){
    duration = Math.ceil($('audio')[0].duration);
    $('#duration').html(duration);
});

Note that this requires that the <script> tag be after the <audio> tag in the document.

Alternatively, you can tweak your logic slightly, so that the code that updates the duration always runs (but fails gracefully if it gets a NaN):

function updateDuration() {
    var duration = Math.ceil($('audio')[0].duration);
    if (duration)
        $('#duration').html(duration);
}

$(document).ready(function(){
    $('audio').on('loadedmetadata', updateDuration);
    updateDuration();
});
like image 127
Casey Chu Avatar answered Sep 28 '22 18:09

Casey Chu