Get audio duration on Chrome for Android

怎甘沉沦 提交于 2019-11-30 09:06:22

EDIT: Using the durationchange event is much easier. First the 0 is being output, but as soon as the file is loaded (that's where loadedmetadata fails I guess) the updated and real duration will be output.

audio.addEventListener('durationchange', function(e) {
    console.log(e.target.duration); //FIRST 0, THEN REAL DURATION
});



OLD WAY (ABOVE IS MUCH FASTER)

Looks like this "bug" (if this is actually a real bug) is still around. Chrome (40) for Android still outputs 0 as the audio files duration. Researching the web didn't get me a solution but I found out the bug also occurs on iOS. I figured I should post my fix here for you guys.

While audio.duration outputs 0, logging audio outputs the object and you can see that the duration is displayed just right there. All this is happening in the loadedmetadata event.

audio.addEventListener('loadedmetadata', function(e) {
    console.log(e.target.duration); //0
});

If you log audio.duration in the timeupdate event though, the real duration is being output. To only output it once you could do something like:

var fix = true;
audio.addEventListener('timeupdate', function(e) {
    if(fix === true) {
        console.log(e.target.duration); //REAL DURATION
        fix = false;
    }
    console.log(e.target.currentTime); //UPDATED TIME POSITION
});

I'm not sure why all this is happening. But let's be happy it's nothing serious.

There is a different approach you can try but, if duration doesn't work with your device (which IMO is a bug) then it's likely this doesn't either; worth a shot though:

audio.seekable.end(audio.seekable.length-1);

or even

audio.buffered.end(audio.buffered.length-1);

though the latter is dependent on content being loaded which in this case probably then won't help.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!