Issue with getting duration attribute of an audio

2019-07-27 12:11发布

问题:

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 );
    });

回答1:

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.



回答2:

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 );
});