如何获得 html5 音频的持续时间 [英] How can I get the html5 audio's duration time

查看:33
本文介绍了如何获得 html5 音频的持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面中有一个 html5 标签,但我怎么知道它的持续时间?

I have a html5 <audio> tag in page, but how can I know its duration time?

<audio controls="">
    <source src="p4.2.mp3">
</audio>

推荐答案

2020 解决方案:

当音频元数据尚未加载时,您将获得 undefinedNaN(不是数字).因此有人建议使用onloadedmetadata来确保先获取音频文件的元数据.此外,大多数人没有提到的是,您必须像这样使用 [0] 来定位音频 DOM 元素的第一个索引:

You will get undefined or NaN (not a number) when the audio metadata isn't loaded yet. Therefore some people suggested to use onloadedmetadata to make sure the metadata of the audio file is fetched first. Also, what most people didn't mention is that you have to target the first index of the audio DOM element with [0] like this:

-- 原生 Javascript:

-- Vanilla Javascript:

var audio = document.getElementById('audio-1');
audio.onloadedmetadata = function() {
  alert(audio.duration);
};

如果这行不通,请尝试此操作,但不太可靠且依赖于用户连接:

If this won't work try this, however not so reliable and dependent on users connection:

setTimeout(function () {
    var audio = document.getElementById('audio-1');
    console.log("audio", audio.duration);
}, 100);

-- JQuery:

$(document).ready(function() {
   var audio = $("#audio-1")[0];
   $("#audio-1").on("loadedmetadata", function() {
       alert(audio.duration);
   }); 
});

这篇关于如何获得 html5 音频的持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆