Using JavaScript to Control the Playback of Audio Tag in HTML5

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

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%22%20type=%22audio/mpeg%22%20/ type="audio/mpeg" />
          Your browser does not support the audio tag.
       
</audio>

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

image1.png

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.

Look at the HTML Markup and its output in a 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:


image2.png
Now to apply the action in the above HTML Markup, we need to write some JavaScript. 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.

image3.gif

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

Credit: http://msdn.microsoft.com/en-us/library/ie/gg589529%28v=vs.85%29.aspx

I hope you like it. Thanks.