Using JavaScript to Control the Playback of Audio Tag in HTML5


In this post you will learn how to control the audio playback of <audio> tag in HTML5 by using JavaScript logics.

HTML5 defines a new element which specifies a standard way to embed an audio file on a web page using the <audio> element.

To play an audio file in HTML5, this is all you need:

        <audio controls="controls">
            <source src="http://domain.com/inanhq.mp3" type="audio/mp3" />
            <source src=" http://domain.com/inanhq.mp3" type="audio/mpeg" />
          Your browser does not support the audio tag.
        </audio>

Above <audio> element adds audio controls like play, pause and volume automatically on the web page. Here is the output.


We can use text content between the <audio> and </audio> tags for browsers that do not support the <audio> element.

The <audio> element allows multiple <source> elements. <source> elements can link to different audio files. The browser will use the first recognized format.

Now to customize the audio controls like play, pause and volume and even add new rewind, forward, restart buttons we just need to add some JavaScript logics.

Look at the HTML Markup and its output in browser.

HTML Markup:

    <h1>JavaScript Controlled Audio Playback</h1>
    <div>
        <p>
            Type sample audio url having .mp3 exetension and click on play button.
            <br />
            <input type="text" id="audiofile" size="80" value="" />
        </p>
        <audio id="myaudio">
          Audio Tag not Supported.
        </audio>
        <button id="play" onclick="playAudio();">
          Play
        </button>
   
        <button onclick="rewindAudio();">
          Rewind
        </button>
        <button onclick="forwardAudio();">
          Fast forward
        </button>
        <button onclick="restartAudio();">
          Restart
        </button>
    </div>

Output in Browser:





Now to apply the action in above HTML Markup we need to write JavaScript logics. Find the JavaScript Methods below:

    <script type="text/javascript">
        // Global variable to track current file name.
        var currentFile = "";
        function playAudio() {
            // Check for audio element support.
            if (window.HTMLAudioElement) {
                try {
                    var oAudio = document.getElementById('myaudio');
                    var btn = document.getElementById('play');
                    var audioURL = document.getElementById('audiofile');

                    //Skip loading if current file hasn't changed.
                    if (audioURL.value !== currentFile) {
                        oAudio.src = audioURL.value;
                        currentFile = audioURL.value;
                    }

                    // Tests the paused attribute and set state.
                    if (oAudio.paused) {
                        oAudio.play();
                        btn.textContent = "Pause";
                    }
                    else {
                        oAudio.pause();
                        btn.textContent = "Play";
                    }
                }
                catch (e) {
                    // Fail silently but show in F12 developer tools console
                    if (window.console && console.error("Error:" + e));
                }
            }
        }
        // Rewinds the audio file by 30 seconds.

        function rewindAudio() {
            // Check for audio element support.
            if (window.HTMLAudioElement) {
                try {
                    var oAudio = document.getElementById('myaudio');
                    oAudio.currentTime -= 30.0;
                }
                catch (e) {
                    // Fail silently but show in F12 developer tools console
                    if (window.console && console.error("Error:" + e));
                }
            }
        }

        // Fast forwards the audio file by 30 seconds.

        function forwardAudio() {

            // Check for audio element support.
            if (window.HTMLAudioElement) {
                try {
                    var oAudio = document.getElementById('myaudio');
                    oAudio.currentTime += 30.0;
                }
                catch (e) {
                    // Fail silently but show in F12 developer tools console
                    if (window.console && console.error("Error:" + e));
                }
            }
        }

        // Restart the audio file to the beginning.

        function restartAudio() {
            // Check for audio element support.
            if (window.HTMLAudioElement) {
                try {
                    var oAudio = document.getElementById('myaudio');
                    oAudio.currentTime = 0;
                }
                catch (e) {
                    // Fail silently but show in F12 developer tools console
                    if (window.console && console.error("Error:" + e));
                }
            }
        }
    </script>

If you know the JavaScript, then you will not find any difficulties to understand above methods.

Now, let’s see the <audio> tag in action.




Note: Download the attached project to test and you need internet connection because I am using remote server to get audio file.


I hope you like it. Thanks.

Credit: http://msdn.microsoft.com/en-us/library/ie/gg589529(v=vs.85).aspx

Comments

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System