Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda