Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 470
hh54188 Avatar asked Jun 26 '12 08:06

hh54188


People also ask

How do you find the duration of a video in HTML?

The duration property returns the length of the current audio/video, in seconds. If no audio/video is set, NaN (Not-a-Number) is returned.

Why is video duration NaN?

The Video duration property is a read-only property. The Video duration function returns “NaN” if no video is set whereas if the video is streamed and has no predefined length, it returns “Inf” (Infinity). Below program illustrates the Video duration Property : Example: Getting the length of a video.


Video Answer


1 Answers

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);    });  }); 
like image 86
AlexioVay Avatar answered Oct 12 '22 10:10

AlexioVay