Skip to content Skip to sidebar Skip to footer

How To Prevent Broken Audio Src From Printing Error Message In Console?

I have a webpage where the user clicks a button and a audio starts to play. But if the source url is incorrect, it prints i

Solution 1:

The error is generated when you call .play(), not when you assign the invalid src. To suppress it, as the error indicates, you need to catch the error thrown by the promise that .play() returns:

var myAudio = newAudio();
myAudio.src = "myAudioSrc (incorrect url)";
console.log('src has been assigned');
myAudio.play()
  .catch(() =>void0);

Because embedded snippets wouldn't show the error anyway, here's an example on JSFiddle to illustrate the difference: https://jsfiddle.net/smjy5b9u/

Solution 2:

You can simply catch the promise returned (if any), even though this message is IMM Chrome's implementation just being too verbose.

var p = newAudio('foo').play();
// check we actually have a Promise (older browser may not return this)if(p)
  p.catch(function(e){/*silent*/});

Post a Comment for "How To Prevent Broken Audio Src From Printing Error Message In Console?"