2016 年检测到但今天(2019 年 3 月)仍然存在的 Chrome 中的一个错误是此行为背后的根本原因。在某些情况下audioElement.duration
会返回Infinity
。
此处和此处的Chrome 错误信息
以下代码提供了避免该错误的解决方法。
用法:创建您的audioElement
,并一次调用此函数,提供您的audioElement
. 当返回promise
解析时,audioElement.duration
属性应该包含正确的值。(它也解决了同样的问题videoElements
)
/**
* calculateMediaDuration()
* Force media element duration calculation.
* Returns a promise, that resolves when duration is calculated
**/
function calculateMediaDuration(media){
return new Promise( (resolve,reject)=>{
media.onloadedmetadata = function(){
// set the mediaElement.currentTime to a high value beyond its real duration
media.currentTime = Number.MAX_SAFE_INTEGER;
// listen to time position change
media.ontimeupdate = function(){
media.ontimeupdate = function(){};
// setting player currentTime back to 0 can be buggy too, set it first to .1 sec
media.currentTime = 0.1;
media.currentTime = 0;
// media.duration should now have its correct value, return it...
resolve(media.duration);
}
}
});
}
// USAGE EXAMPLE :
calculateMediaDuration( yourAudioElement ).then( ()=>{
console.log( yourAudioElement.duration )
});