Search code examples
javascriptvue.jshtml5-audioweb-audio-api

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)

Solution

  • 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>