Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

html - How can I get the html5 audio's duration time

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

<audio controls="">
    <source src="p4.2.mp3">
</audio>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

2020 solution:

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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...