code prettify

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.

1 comment:

  1. Nice way of identifying if browser can play audio or not.

    ReplyDelete