Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
Audio Constructor in Javascript is returning NaN

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
    });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!