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

296
Visualizações
Audio - how to check if path is valid

I am trying to play an audio file:

path = '/public/recordings/weekday/1.mp3'
const audio = new Audio(path)
audio.play()

If the path is NOT valid then the following warning appears in the console:

Uncaught (in promise) DOMException: Failed to load because no supported source was found.

is there a javascript method to check if the file exists so I can avoid calling play on it?

I imagine the answer could be in this doc:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType

I did find a workaround but I do NOT like it:

audio.addEventListener('error', function (err) {
   if (err.path[0].error.message.includes('DEMUXER_ERROR_COULD_NOT_OPEN')) {
      this.handleError()
    } else {
      this.handleSomeOtherError()
    }
}.bind(this), false)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Using a promise helped:

const playPromise = this.audio.play();
if (playPromise !== undefined) {
    playPromise.then(function() {
      console.log('Automatic playback started!!')
    }).catch(function(error) {
       console.log(error)
       this.handleError()
    }.bind(this), false);
 }
about 4 years ago · Juan Pablo Isaza Relatório

0

Throw it in a promise.

function Function() {
path = 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3';
var audio = new Audio(path);
var playPromise = audio.play();
if (playPromise !== undefined) {
  playPromise.then(_ => {
    audio.setAttribute("controls", "controls");
    document.body.appendChild(audio);
    audio.play();
  })
  }
  }
<button onclick="Function()">Try it</button>

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