code prettify

Tuesday 28 October 2014

Handling errors while using html5 audio


While using the <audio> tag, there are chances of errors happening while playing the audio file.

It may be due to one of the below reasons:
- Intermittent connectivity
- Invalid "src" being set
- An audio format which the browser cannot decode and so cannot play
- Due to corrupted audio file being played

It would be better if we could know about these and be prepared to handle them instead of putting the user through a very bad experience.

The audio object has an error event which can be listened to for any errors. The "audio" attribute on the audio element can also be accessed to get the last error which had occurred. It returns a "MediaError" object representing the current error state of the element. It returns null if there is no error.

Types of error:
Each of the below error types has a corresponding associated number that is the error code produced by the "event".

- MEDIA_ERR_ABORTED(1)
    Occurs when the fetching process for the media resource was aborted by the user agent (browser) at the user's request.
    
- MEDIA_ERR_NETWORK(2)
    A network error of some description caused the user agent (browser) to stop fetching the media resource (after the resource was established to be usable).

- MEDIA_ERR_DECODE(3)
    An error of some description occurred while decoding the media resource (after the resource was established to be usable).

- MEDIA_ERR_SRC_NOT_SUPPORTED(4)
    The media resource indicated by the src attribute or assigned media provider object was not suitable.

Sample Code:
<audio src="sample.mp3"></audio> 
<script>     
    var audioElem = document.document.getElementsByTagName("audio")[0];
    
    // Add event to detect error and display error code      
    audioElem.addEventListener("error", function () {
        if (audioElem.error) {
            alert(audioElem.error.code);
        }
    }, false);
</script> 

References:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events#Error_handling
https://html.spec.whatwg.org/#error-codes

No comments:

Post a Comment