Issue with getting duration attribute of an audio

2019-07-27 12:30发布

I have a problem with getting the metadata of an audio/mpeg (mp3).

For example, I'm using JS to get the duration of the audio file and when the cache is empty the duration value returns "Infinity" (NaN).

I have tried with the events/attributes preload and onloadedmetadata and always when the cache is empty I can't get the duration and other properties of an audio.

Note: The problem is only when I clean the cache (or when the visitors comes first time to the page).

    audioElement = new Audio('http://www.html5rocks.com/en/tutorials/audio/quick/test.mp3');
    console.log(audioElement);
    audioElement.addEventListener("loadedmetadata", function(_event) {
    var duration = audioElement.duration;
    console.log( duration );
    });

2条回答
Bombasti
2楼-- · 2019-07-27 12:46

Perhaps it is because your media is streaming?

See https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement

duration Read only double
The length of the media in seconds, or zero if no media data is available. If the media data is available but the length is unknown, this value is NaN. If the media is streamed and has no predefined length, the value is Inf.

查看更多
迷人小祖宗
3楼-- · 2019-07-27 12:47
audioElement = new Audio('http://www.html5rocks.com/en/tutorials/audio/quick/test.mp3');
    console.log(audioElement);
    audioElement.addEventListener("loadedmetadata", function(_event) {
    var duration = audioElement.duration;
    console.log( duration );
});
查看更多
登录 后发表回答