Chromium内核浏览器中HTML Audio duration返回无穷大问题求助
Chromium浏览器中audioElement.duration返回无穷大,Firefox正常的解决方案
调用audioElement.duration时,Chromium内核浏览器(如Chrome、Edge)返回无穷大,但Firefox能正常获取本地同一目录下音频文件的时长。相关代码如下:
console.log("Welcome to Spotify | clone"); let songIndex = 0; const masterPlay = document.getElementById("masterPlay"); const progressBar = document.getElementById("progressBar"); const gif = document.getElementById("gif"); const audioElement = document.getElementById("song") // let audioElement=new Audio('./1.mp3') // Handling play pause and click masterPlay.addEventListener('click', () => { if (audioElement.paused || audioElement.currentTime <= 0) { audioElement.play(); masterPlay.classList.remove("fa-circle-play"); masterPlay.classList.add("fa-circle-pause"); gif.style.opacity = 1; } else { audioElement.pause(); masterPlay.classList.remove("fa-circle-pause"); masterPlay.classList.add("fa-circle-play"); gif.style.opacity = 0; } }); // EventListeners audioElement.addEventListener("timeupdate", () => { progress = ((audioElement.currentTime / audioElement.duration) * 100); progressBar.value = progress; console.log(audioElement.currentTime) });
已尝试以下方案:
- 更换浏览器(仅Firefox正常)
- 更换音频文件(部分音频在Chrome仍异常)
- 使用HTML audio元素(问题依旧)
- 使用JS Audio()构造函数(问题未解决)
可行解决方法
- 等待音频元数据加载完成后操作
Chromium需要等待音频元数据加载完毕才能正确读取时长,通过监听loadedmetadata事件确保时长有效:
// 新增监听元数据加载事件 audioElement.addEventListener('loadedmetadata', () => { console.log('音频时长:', audioElement.duration); }); // 修改timeupdate事件,避免无穷大时计算出错 audioElement.addEventListener("timeupdate", () => { if (!isFinite(audioElement.duration)) return; progress = ((audioElement.currentTime / audioElement.duration) * 100); progressBar.value = progress; console.log(audioElement.currentTime) });
检查并转码音频文件
部分非标准编码的MP3文件在Chromium中无法正确识别元数据,可将音频转码为标准MP3格式(如使用LAME编码器),确保文件包含完整的时长信息。使用本地服务器运行项目
直接通过file://协议打开本地HTML文件时,Chromium的媒体权限受限,容易导致元数据读取失败。建议使用本地服务器(如Node.js的http-server、Python的python -m http.server),通过http://localhost访问项目。
内容的提问来源于stack exchange,提问作者Debarka Mondal
相关产品推荐
相关产品推荐

