code prettify

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>

3 comments:

  1. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon. school websites uk

    ReplyDelete