Neablis Neablis - 2 months ago 22
HTML Question

How to check if HTML5 audio has reached different errors

Specifically, if one of the 206 requests for audio fails and buffering stops, is there a way to detect that state? Or should I have to check if buffering stopped by comparing the buffered amounts against past amounts?

Also how can I check if the specified source fails, could you then point it to another source?

Answer

1. Specifically, if one of the requests for audio fails and buffering stops, is there a way to detect that state?

Yes, there is few ways to do this! But if you want to catch the error type you can attach the error event listener to the sources:

$('audio').addEventListener('error', function failed(e) {
   // audio playback failed - show a message saying why
   // to get the source of the audio element use $(this).src
   switch (e.target.error.code) {
     case e.target.error.MEDIA_ERR_ABORTED:
       alert('You aborted the video playback.');
       break;
     case e.target.error.MEDIA_ERR_NETWORK:
       alert('A network error caused the audio download to fail.');
       break;
     case e.target.error.MEDIA_ERR_DECODE:
       alert('The audio playback was aborted due to a corruption problem or because the video used features your browser did not support.');
       break;
     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
       alert('The video audio not be loaded, either because the server or network failed or because the format is not supported.');
       break;
     default:
       alert('An unknown error occurred.');
       break;
   }
 }, true);

2. Could you then point it to another source?

Inside the error handler function you can change the source using the src property of the audio element:

var audio = $(this);
audio.src = "new-audio-file.mp3";
audio.load();

Another option is to add multiple source to the same audio tag using this syntax:

<audio>
    <source id="audio_player_ogv" src="test.ogv" type="audio/ogg" />
    //In case that you can't load the ogv file it will try to load test.mp3
    <source id="audio_player_mp3" src="test.mp3" type="audio/mpeg" />
</audio>

3. About manage multiple audio files

I would suggest to use a plugin if you are thinking to manage 206 audio files. I have been using SoundManager2 for a while and it's very good!