You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取音频播放时长遇NaN问题:audio.duration返回NaN求助

audio.duration 返回 NaN 问题的解决方案

问题根源

你遇到的duration返回NaN的问题,本质是音频元数据尚未加载完成。在创建Audio实例后立即读取duration,浏览器还没完成音频文件的元数据解析,无法返回有效时长,进而导致进度计算出现NaN。

可行解决方案

1. 监听loadedmetadata事件(最推荐)

当音频元数据加载完成时,浏览器会触发loadedmetadata事件,此时duration会被正确赋值。同时搭配timeupdate事件,可以实时更新播放进度:

let audioElement = new Audio('1.mp3');
let myProgressBar = document.getElementById('myProgressBar');

// 等待元数据加载完成
audioElement.addEventListener('loadedmetadata', () => {
    // 初始化进度
    updateProgress();
    // 实时监听播放进度变化
    audioElement.addEventListener('timeupdate', updateProgress);
});

function updateProgress() {
    // 避免异常情况
    if (isNaN(audioElement.duration)) return;
    let progress = parseInt((audioElement.currentTime / audioElement.duration) * 100);
    console.log("progress", progress);
    myProgressBar.value = progress;
}

2. 设置预加载策略

给Audio元素设置preload="metadata",告诉浏览器优先加载音频元数据(而非整个文件),能加快duration的获取速度:

let audioElement = new Audio();
audioElement.preload = 'metadata';
audioElement.src = '1.mp3';

// 后续依然通过loadedmetadata事件处理
audioElement.addEventListener('loadedmetadata', () => {
    updateProgress();
    audioElement.addEventListener('timeupdate', updateProgress);
});

function updateProgress() {
    if (isNaN(audioElement.duration)) return;
    let progress = parseInt((audioElement.currentTime / audioElement.duration) * 100);
    console.log("progress", progress);
    myProgressBar.value = progress;
}

3. 异常兜底处理

如果需要兼容音频加载失败的场景,可以在进度计算前增加判断,避免NaN影响页面逻辑:

function updateProgress() {
    if (isNaN(audioElement.duration) || audioElement.duration === 0) {
        myProgressBar.value = 0;
        return;
    }
    let progress = parseInt((audioElement.currentTime / audioElement.duration) * 100);
    console.log("progress", progress);
    myProgressBar.value = progress;
}

内容的提问来源于stack exchange,提问作者Arpit_LoveCoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 10:35:40