Javascript/Jquery to control HTML5 audio elements

Posted: November 17, 2012 by Sankar Vijayakumar in HTML5, Javascript
Tags: , , , , , , ,

Jquery to control HTML5 audio elements

html5 javascript Automatically start playing the audio on page load

preload audio

html5 jquery play pause audio

html5 jquery Trigger events at certain times in audio

jquery Mute audio

Before checking the javascript code, let’s have a look at the Html5 audio tag:-

<audio id="bg_audio" controls="controls">
<source src="audio_file.ogg" type="audio/ogg">
<source src="audio_file.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

How to handle/control the HTML5 audio elements?

  1. Automatically start playing the audio on page load:
    Just add the attribute: autoplay=”autoplay” with in the audio tag as show below:

    <audio id="bg_audio" controls="controls" autoplay="autoplay" >
    <source src="audio_file.ogg" type="audio/ogg">
    <source src="audio_file.mp3" type="audio/mpeg">
    Your browser does not support the audio element.
    </audio>
  2. Play the audio manually:

    document.getElementById('bg_audio').play();
  3. Pause the audio:

    $('#bg_audio').trigger("pause");
  4. Play the audio:

    $('#bg_audio').trigger("play");
  5. Mute audio:

    document.getElementById('bg_audio').muted = true;
  6. Unmute audio:

    document.getElementById('bg_audio').muted = false;
  7. Trigger events at certain times in audio playback:

    $("#bg_audio").bind('timeupdate', function(){
        if(this.currentTime >= 11 && this.currentTime <= 12){
            //Your code.
        }
    });
  8. Check whether the audio is being played:

    document.getElementById('bg_audio').addEventListener('play', function(){
        //Your code.
    });
  9. Check whether the audio is paused:

    document.getElementById('bg_audio').addEventListener('pause', function(){
        //Your code.
    });
  10. Check whether the audio has finished playing:

    document.getElementById('bg_audio').addEventListener('ended', function(){
        //Your code.
    });

So the final question:

How to stop html5 audio element using javascript/jquery?

Unfortunately there’s no way to stop the audio, we need to pause the audio and change the current playing time to zero as mentioned earlier.

Click here, for more information.

Jquery to control HTML5 audio elements

html5 javascript Automatically start playing the audio on page load

Comments
  1. George Hardwick says:

    Nice breakdown of some pretty complicated stuff. It looks like another language until somebody explains it all. Nice post!

    Like

  2. Code.
    My daughter speaks in “programming” languages too.
    But they are a mystery to me.
    Thank goodness for people who understand this, and keep things up and running!

    Like

  3. teodora says:

    This is awesome Html5 Soundboard -> http://bit.ly/15878zW

    Like

How's it? Your comments and suggestions...