This tutorial follows my earlier HTML5 audio API tutorial. In it, we will learn how to control audio with jQuery. This is handy if you are developing a dynamic application that uses several audio media and wants to control them efficiently from your jQuery script. Let’s get rolling!
How Far We Can Control?
Well, we can control almost every feature that the HTML5 player provides by default, like play/pause/volume up/down, mute on/off, and additional functionality like stop, forward/backward capability, etc.
So, if you have N number of audio files on a single page, and instead of letting users deal with N audio players, you can give it an efficient interface and control what to play/stop, etc, with jQuery.
The Audio Media:
Let’s use the following code as our HTML5 code for the audio media:
<audio class="audioDemo" controls preload="none">
<source src="audio/pitbull.mp3" type="audio/mpeg">
<source src="audio/music.ogg" type="audio/ogg">
</audio>
Code language: JavaScript (javascript)
We have kept two media because of compatibility issues on browsers, so the alternative one is being loaded.
Loading The Audio With jQuery:
As you can see in the above HTML5 code, we have set the “preload” option to “none,” which means no information about the audio file will be loaded on the page load, neither the audio file nor any metadata. We will do them by ourselves from jQuery to boost the page load performance. Let’s use the following code to load the audio:
$(".audioDemo").trigger('load');
Code language: JavaScript (javascript)
We can also add an event listener to let us know when it’s loaded. However, the event will be triggered immediately after the metadata is loaded and the audio starts loading. But it won’t wait till the audio loads in full, which usually loads on demand. To do something after the loading, use the following code before triggering the load event:
$(".audioDemo").bind("load",function(){
$(".alert-success").html("Audio Loaded succesfully");
});
Code language: JavaScript (javascript)
Play/Pause/Stop Audio:
Start playing audio and pause. It is pretty easy to handle; you need to trigger corresponding events as below:
//starts playing
$(".audioDemo").trigger('play');
//pause playing
$(".audioDemo").trigger('pause');
Code language: JavaScript (javascript)
However, there is no ready event to stop audio, so we will need to do it with the help of ‘pause’ event and another property named “currentTime,” which indicates the current playing time. Here is what we will do to stop:
function stopAudio(){
//pause playing
$(".audioDemo").trigger('pause');
//set play time to 0
$(".audioDemo").prop("currentTime",0);
}
Code language: JavaScript (javascript)
Forward/Backward Capability:
The Default HTML5 player doesn’t provide this facility, but we can easily make such functionality with a little jQuery code. Here is a small example code to do so:
//forward the music about 5 seconds
$(".audioDemo").prop("currentTime",$(".audioDemo").prop("currentTime")+5);
//backward the music about 5 seconds
$(".audioDemo").prop("currentTime",$(".audioDemo").prop("currentTime")-5);
Code language: JavaScript (javascript)
Volume Up/Down:
The audio player has its own “volume,” properly which can be controlled with jQuery as below:
function volumeUp(){
var volume = $(".audioDemo").prop("volume")+0.2;
if(volume >1){
volume = 1;
}
$(".audioDemo").prop("volume",volume);
}
function volumeDown(){
var volume = $(".audioDemo").prop("volume")-0.2;
if(volume <0){
volume = 0;
}
$(".audioDemo").prop("volume",volume);
}
Code language: JavaScript (javascript)
We need to keep checking whether the volume reaches its most significant or minimum value. Otherwise, a JavaScript exception error will be thrown.
Mute On/Off:
We can instantly turn audio off and turn it on to its earlier volume level quickly with the use of the “muted” property. See the example code below, which toggles the current mute state:
function toggleMuteAudio(){
$(".audioDemo").prop("muted",!$(".audioDemo").prop("muted"));
}
Code language: JavaScript (javascript)
Final Words:
I hope this small tutorial on controlling HTML5 audio with jQuery will help you develop audio/music-driven web applications quickly. If you are having any issues running any example or with the demo, please let me know by commenting here. Happy coding 🙂
newlandsvalley says
I’m using the latest releases of Firefox and Chrome on Ubuntu 12.04. For me, your demo works fine in Firefox but not at all in Chrome. Have you noticed this?
I use mac, not ubuntu. But as being *nix based, should have been behaving in same way. However, thanks for noticing and reporting. I will check. Thanks.
Not sure what the problem was. I downloaded your script, invoked the initialisation differently and all works fine across Chrome, Opera and Firefox. Very useful – thanks.
Hi, I have followed your tutorial and it works perfect. What I don’t understand clearly is, here you are using HTML5 audio player. Is it the same as this JavaScript/jQuery: audio = new Audio(‘test.mp3’); audio.play(); Or is this JavaScript player, and not HTML5 audio player? Thanks in advanced for your answer!
HTML5 consists of all new features of css/javascripts which are supported by browsers. You can’t use this javascript code on a old browser version that doesn’t have HTML5 support. Hope this helps!
is there any option to only show muted control, please reply
nice one , helped me a lot , thanks 🙂
I’m using a HTML5 player in joomla that’s control by jquery. It keeps looping the song. Is there a way to stop the repeat?
Hi there, is there a way to exclude or deactivate the volume control from the standard html5 audio control.
im using multiple audio tags
i want it to be played one at a time
this is the code
aoa… dear how to play songs using this tag if we store path of song file in database
Looking at the “Control HTML5 Audio With Jquery” and “Javascript Audio Controller Demo” pages and I still have no idea how to make an audio player using jquery. I never saw any download links on the demo page. Is there source code on GITHUB. The demo page also uses bootstrap for the buttons. I real working demo that can be downloaded would make more sense. Thanks.
Hi, good explication. In this moment I have a problem, I not know control the preload for created a progress bar of preload of audio.
How refresh the tag of audio?, cuz already im supported, 3 diferent source, when are available, so already i add the new source with append (jqeury) but, some times the audio appear desactive and others times work, when appear desactive, just reload the page, and work….. if somebady can help me i would apprentice it, and thaks for the future responde
I have a list of tracks that I would like to play over and over randomly until I click a stop button. Any clues on how to set that up?
I have sound track for every page. Want to turn off the audio when turn next page. Also, the audio on the earlier page must start from the beginning if I visit that page again. How should code. I have put html5 audio player.
Thank you very much.
If you trigger the .load() method for that player, it should reset the audio.
I am creating Rss Feeds [https://mySocialFeeds.com/] which I am importing into the audio app to play different songs / playlists. Works really well!