javascriptajaxerror-handlingmedia-playersoundmanager2

How do I detect/handle a browser's failure to play a media file


I'm using a JavaScript library to play mp3 files. Due to circumstances out of my control, I periodically link to a file that cannot be played. When this happens, I see a message in Firebug explaining that the file could not be decoded.

Media resource https://example.com/bad_file.mp3 could not be decoded.

screen capture of firebug message concerning bad file
Click here to see the behavior in action on jsfiddle

Since there is nothing I can do to replace the files, I'm looking for a way of determining whether or not a file can be played. The framework provides an onerror() method for when the script itself fails to load, but nothing for when the file can't be played.

While an answer specific to SoundManager2 would be acceptable, I would prefer a solution that is independent of any particular library or framework.


Solution

  • Generally you can add an onerror event listener to elements that load resources. So for instance since you are doing audio you would attach an event listener to the audio element

    //assume this html:
    //<audio id="myaudio" src="http://badurl.com/mp3.mp3"></audio>
    document.getElementById("myaudio").addEventListener("error",function(event){
      //do error handling here
    });
    

    For SoundManager2 specifically you can pass in a onload callback option, it will be passed a success variable, true for it loaded false if not, API reference

    var mySound = soundManager.createSound({
      id: 'aSound',
      url: 'http://badurl.com/mp3.mp3',
      onload:function(success){
         if(!success){
            //error happened
         }
      } 
    });
    mySound.play();