I was trying to to get duration of audio files using creating audio Constructor in a for Each Loop but audioElement.duration is returning NaN only. Here's my code.
let audioArray = [
'1.mp3',
'2.mp3',
'3.mp3',
'4.mp3'
]
let audioElement;
audioArray.forEach((element)=>{
audioElement = new Audio(element);
console.log(audioElement.duration);
})
The browser won't know the duration until enough of the file has been downloaded, so you need to wait for the correct event.
See this snippet from https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement
audioElement.addEventListener('loadeddata', () => {
let duration = audioElement.duration;
// The duration variable now holds the duration (in seconds) of the audio clip
})
In your example, to log out the durations you would do this:
let audioArray = [
'1.mp3',
'2.mp3',
'3.mp3',
'4.mp3'
]
audioArray.forEach((element)=>{
let audioElement = new Audio(element);
audioElement.addEventListener('loadeddata', () => {
console.log(`${element} duration:`, audioElement.duration);
});
});