Understanding the HTML Audio duration
Property
The HTML Audio duration
property provides a way to access the total length of an audio file in seconds. This property is read-only and gives valuable information about the media being played, allowing developers to create accurate progress indicators, seek bars, and display the total length of an audio track.
What is the duration
Property?
The duration
property is part of the HTMLAudioElement
interface. It returns a floating-point number representing the length of the audio in seconds. If the duration is unknown (e.g., the audio is still loading or is a live stream), the property returns NaN
(Not-a-Number).
Purpose of the duration
Property
The main purposes of the duration
property are to:
- Determine the total playback time of an audio file.
- Facilitate the creation of accurate progress bars and seek functionality.
- Display the total length of an audio track in a user-friendly format (e.g., minutes and seconds).
- Check if the audio’s duration is available before performing certain actions.
Syntax
The duration
property is accessed directly from an HTMLAudioElement
object:
let audioDuration = audioElement.duration;
audioElement
: A reference to an<audio>
element in the DOM.audioDuration
: A floating-point number representing the duration of the audio in seconds, orNaN
if the duration is unknown.
Property Values
Value | Type | Description |
---|---|---|
`Number` | Floating-point | The duration of the audio in seconds. |
`NaN` | Number | Returned if the duration is unknown (e.g., while loading, live stream). |
Practical Examples
Let’s explore how to use the duration
property with practical examples.
Basic Example: Displaying Audio Duration
This example demonstrates how to get and display the duration of an audio file when its metadata is loaded.
<audio id="audioExample1" controls src="https://www.w3schools.com/html/horse.ogg"></audio>
<p>Duration: <span id="durationDisplay1"></span> seconds</p>
<script>
const audioElement1 = document.getElementById("audioExample1");
const durationDisplay1 = document.getElementById("durationDisplay1");
audioElement1.addEventListener("loadedmetadata", function() {
const duration = audioElement1.duration;
durationDisplay1.textContent = duration.toFixed(2);
});
</script>
Output:
(An audio player with controls will appear. Once the metadata is loaded, the duration in seconds will be displayed below the player.)
Duration: (Audio Duration in Seconds) seconds
Example: Formatting Duration into Minutes and Seconds
This example formats the audio duration into a more readable “minutes:seconds” format.
<audio id="audioExample2" controls src="https://www.w3schools.com/html/horse.ogg"></audio>
<p>Duration: <span id="durationDisplay2"></span></p>
<script>
const audioElement2 = document.getElementById("audioExample2");
const durationDisplay2 = document.getElementById("durationDisplay2");
audioElement2.addEventListener("loadedmetadata", function() {
const duration = audioElement2.duration;
const minutes = Math.floor(duration / 60);
const seconds = Math.floor(duration % 60);
const formattedDuration = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
durationDisplay2.textContent = formattedDuration;
});
</script>
Output:
(An audio player with controls will appear. Once the metadata is loaded, the duration in minutes and seconds will be displayed below the player.)
Duration: (Minutes):(Seconds)
Example: Creating a Progress Bar
This example demonstrates how to create a progress bar that reflects the audio’s playback progress, using the duration
property to calculate the total length.
<audio id="audioExample3" controls src="https://www.w3schools.com/html/horse.ogg"></audio>
<br>
<progress id="progressBar3" value="0" max="100"></progress>
<script>
const audioElement3 = document.getElementById("audioExample3");
const progressBar3 = document.getElementById("progressBar3");
audioElement3.addEventListener("loadedmetadata", function() {
progressBar3.max = audioElement3.duration;
});
audioElement3.addEventListener("timeupdate", function() {
progressBar3.value = audioElement3.currentTime;
});
</script>
Output:
(An audio player with controls will appear, along with a progress bar that updates as the audio plays.)
Example: Handling Unknown Duration (Live Streams)
This example checks if the duration is NaN
and displays a message indicating that the duration is unknown (useful for live streams).
<audio id="audioExample4" controls src="https://www.w3schools.com/html/horse.ogg"></audio>
<p>Duration: <span id="durationDisplay4"></span></p>
<script>
const audioElement4 = document.getElementById("audioExample4");
const durationDisplay4 = document.getElementById("durationDisplay4");
audioElement4.addEventListener("loadedmetadata", function() {
const duration = audioElement4.duration;
if (isNaN(duration)) {
durationDisplay4.textContent = "Duration unknown (Live Stream)";
} else {
durationDisplay4.textContent = duration.toFixed(2) + " seconds";
}
});
</script>
Output:
(An audio player with controls will appear. The duration will either be displayed in seconds or “Duration unknown (Live Stream)” will be displayed if the audio is a live stream or the duration cannot be determined.)
Real-World Applications of the duration
Property
- Audio Players: Displaying the total length of an audio track.
- Podcasting Apps: Showing the duration of podcast episodes.
- Music Streaming Services: Implementing accurate seek bars and progress indicators.
- Audio Editing Software: Providing information about the length of audio clips.
Browser Support
The duration
property is supported by all modern browsers:
- Chrome
- Firefox
- Safari
- Edge
- Opera
Tips and Best Practices
- Always handle
NaN
: Check if the duration isNaN
before using it to avoid unexpected behavior. This is especially important for live streams. - Use
loadedmetadata
event: Ensure you are accessing theduration
property after theloadedmetadata
event has fired to get the correct value. - Format duration for readability: Display the duration in a user-friendly format (e.g., minutes and seconds).
- Update progress bars: Use the
duration
property in conjunction with thecurrentTime
property to create accurate progress bars.
Conclusion
The HTMLAudioElement.duration
property is essential for providing users with information about the length of an audio track. By understanding how to use this property, you can create more informative and user-friendly audio experiences on the web. From displaying the total length of an audio file to creating accurate progress indicators, the duration
property is a valuable tool for any web developer working with audio.