Attempting to play an audio file:
path = '/public/recordings/weekday/1.mp3'
const audio = new Audio(path)
audio.play()
If the path is invalid, a warning message appears in the console:
Uncaught (in promise) DOMException: Failed to load because no supported source was found.
Is there a JavaScript method available to verify if the file exists before attempting to play it?
I believe the solution might be found in this documentation:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType
I did come across a workaround that I am not entirely fond of:
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)