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".

    Occurs when the fetching process for the media resource was aborted by the user agent (browser) at the user's request.
    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).

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

    The media resource indicated by the src attribute or assigned media provider object was not suitable.

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


No comments:

Post a Comment