HTML Audio & Video
HTML DOM Audio duration Property
The duration property returns the total length of the media, in seconds. It is read-only and is only known after the browser has loaded the media's metadata.
Definition and Usage
duration is a floating-point number of seconds. Before metadata has loaded it is NaN, and for live or unbounded streams it is Infinity, so any code that formats it must handle those cases.
Syntax
mediaElement.durationThe safe time to read a meaningful value is inside the loadedmetadata event handler, which fires once the browser knows the media's length and dimensions.
Example: formatting the duration
const video = document.getElementById("myVideo");
video.addEventListener("loadedmetadata", () => {
const total = video.duration; // seconds, e.g. 125.4
if (isFinite(total)) {
const mins = Math.floor(total / 60);
const secs = Math.floor(total % 60).toString().padStart(2, "0");
console.log("Length:", mins + ":" + secs); // e.g. 2:05
} else {
console.log("Live or unknown duration");
}
});Guarding with isFinite() keeps the code from producing NaN:NaN for live streams. Combining duration with currentTime lets you compute the fraction played for a progress bar.
Reading duration too early returns NaN. Always wait for loadedmetadata (or check isNaN) before using it in calculations.
