code prettify

Showing posts with label event. Show all posts
Showing posts with label event. Show all posts

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

Tuesday, 14 October 2014

How to play a series of audio files using HTML5 audio element?

By default the HTML5 <audio> tag allows us to play any one audio file at a time. How do we go about playing a series of audio files that are related but are present separately, lets say something like intro.mp3, part1.mp3, part2.mp3, conclusion.mp3 (something part of our presentation) ?

Well, this can be done with a little bit of coding using the following apis from <audio> element:
- "src" property
- "load" and "play" methods
- "ended" event

Logic:
It goes something like this. We play our first audio file, and then wait or listen for the "ended" event and as soon as it is fired, we change the "src" attribute of <audio> element to our next audio file and call the "load" method to load the file and then call "play" event to play the next audio. This continues for other audio files until we complete all the audio files and then again start from beginning if required.

Code:

<!-- audio element to play our audio files -->
<!-- Notice there is no "src" attribute defined -->
<audio controls id="audio"></audio>


<script>
    var position = 0; // Store position of audio currently playing
    var audioList;    // Store array list of audios to be played
    var audio;        // Store reference to the <audio> element

    window.onload = function () {
        // List of audio files to be played
        audioList = [
            "intro.mp3",
            "part1.mp3",
            "part2.mp3",
            "conclusion.mp3"
        ];

        // Reference to the <audio> element
        audio = document.getElementById("audio");

        // Attach listener to the "ended" event
        audio.addEventListener("ended", nextAudio, false);


        // Play the first audio file when the page loads first time
        playAudio();

    };

    // Handler function to be called when "ended" event is 
    // called on <audio> element that is when the audio files
    // reaches its end
    function nextAudio() {
        // Increase the position to indicate playing next audio file
        position++;

        // If we have reached the end of the list, then start
        // playing from first audio again
        if (position >= audioList.length) {
            position = 0;
        }

        // Play the next audio
        playAudio();
    }

    // Plays the currently positioned audio file
    function playAudio() {
        // Set the "src" of the current audio file, load and play it
        audio.src = audioList[position];
        audio.load();
        audio.play();
    }
</script>

Monday, 13 October 2014

How do you know you have reached the end of an HTML5 audio?

It is very useful to know when an audio file has reached its end in the browser to indicate it visually.

To do so, we can attach an "ended" event on the HTML5 audio element, which happens when the audio reaches the end and stops playing. Using javascript, we can listen to this event and take necessary action.

Example:

<audio id="sample_audio" src="sample.mp3"></audio>

<script>
    var audio_elem = document.getElementById("sample_audio");

    audio_elem.addEventListener("ended", function() {
        alert("The audio file has finished playing");
    });
</script>