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

Sunday 26 October 2014

Assessing HTML5 audio Playback Capabilities using canPlayType method

Assessing <audio> Playback Capabilities

We can test if a particular format of audio can be played by the browser by using the "canPlayType" method of the audio object.

Basically, "canPlayType" method takes an audio format and returns a string that suggests / represents how confident the browser feels that it can play that type of audio.

Below are 3 results from "canPlayType" method:
- "" (Empty string -> cannot play)
- maybe (might be able to)
- probably (browser is reasonably confident that it can play)

Some caution is required when trying to select media in this way, because browsers differ in their way of assessing their ability to play a format.

The different ways in which support is assessed means that the canPlayType method should be used very carefully. A better alternative to it is to provide audio files in more than one format as <source> options.

Example Code:

<audio id="media" controls preload="metadata">
    Audio cannot be played
</audio>
<table id="info" border="1">
    <tr><th>Property</th><th>Value</th></tr>
</table>
<script>
    var mediaElem = document.getElementById("media");
    var tableElem = document.getElementById("info");

    // List of audio files which can be provided for playing
    var mediaFiles = ["sample.ogg", "sample.wav", "sample.mp3"];
    var mediaTypes = ["audio/ogg", "audio/wav", "audio/mp3"];

    // Loop through the audio type list
    // and determine the type which can be played by the browser
    // and set the "src" to it
    for (var i = 0; i < mediaTypes.length; i++) {
        var playable = mediaElem.canPlayType(mediaTypes[i]);

        // if "playable" is empty, then browser can not play the
        // audio format
        if (!playable) {
            playable = "no";
        }

        tableElem.innerHTML += "<tr><td>" + mediaTypes[i] 
            + "</td><td>" + playable + "</td></tr>";

        if (playable == "probably") {
            mediaElem.src = mediaFiles[i];
        }
    }
</script>

In the above example, we are looping through all the audio formats and displaying the info in a table related to whether the browser can play the audio or not. While doing so we are also setting the "src" attribute to audio file which can be played by the browser.

Tuesday 14 October 2014

How to convert audio files from one format to another using "Sound Converter"?

Sound Converter is an open source tool available from Ubuntu Software Center that can be used to convert audio files from one format to another.

Example usage is to generate different formats of same audio file to be used in case of HTML5 <audio> element.


Install it from Ubuntu Software Center



Add a file to be converted, from the browser dialog after clicking on "Add File"


Select the format, the audio file is to be converted to and the place to be saved and then click the "Convert" button in the main window to begin the process.








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

First prototype of HTML5 Audio Player launched

Hi all, we have now started ahead with our first prototype for "the html5 audio player". Please refer the below image:



Currently, we just have the play, pause and volume increase, decrease functionality.

A lot more needs to be done in terms of functionality, design and usability. Looking forward to ideas and help :)

Future plan:
- To include a progress bar to show the progress of the audio
- To manually control the progress by clicking the progress bar

Fork at https://github.com/satejkumar/html5_audio_player.git

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>