Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

audio onError arguments

I'm creating a small HTML5-based website. At some point I want to play a sound. I'm playing the sound like this:

    sound = new Audio(url);
    sound.addEventListener("error", function(e) { 
               console.log("Logging playback error: " + e); });
    sound.load();
    sound.play();

When an error occurs, I can't figure out what's in e. Unfortunately the error occurs only on an iPad, so I can't use Firebug to debug it. Nowhere in the documentation did I found the description of the argument.

Any help would be appreciated.

like image 748
zmbq Avatar asked Jul 29 '12 21:07

zmbq


2 Answers

I probably found that error message object. The error code is in sound.error.code or also e.currentTarget.error.code property and it can contain one of the following 4 digits:

MEDIA_ERR_ABORTED=1
MEDIA_ERR_NETWORK=2
MEDIA_ERR_DECODE=3
MEDIA_ERR_SRC_NOT_SUPPORTED=4

examined it @jsfiddle

like image 114
Stano Avatar answered Sep 28 '22 06:09

Stano


Based on the @Stano answer I've created a function that will output the error message instead of the code number. It uses Object.keys() method from ES6, but it has full support in all major browsers at the time of writing (11/2019).

const getMediaErrorMessage = error => Object.keys(Object.getPrototypeOf(error.currentTarget.error)).find(key => error.currentTarget.error[key] === error.currentTarget.error.code);

This is a snippet presenting the usage of the function:

const getMediaErrorMessage = error => Object.keys(Object.getPrototypeOf(error.currentTarget.error)).find(key => error.currentTarget.error[key] === error.currentTarget.error.code);

const url = 'xxx';  // using wrong url, to get an error
const sound = new Audio(url);
sound.addEventListener('error', e => console.log(`Media error occurred: ${getMediaErrorMessage(e)}`));
sound.load();
sound.play();
like image 42
bearbyt3z Avatar answered Sep 28 '22 08:09

bearbyt3z