• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / Control HTML5 Audio With Jquery

Control HTML5 Audio With Jquery

June 23, 2013 by Rana Ahsan 18 Comments

javascript audio controller

You can consider this tutorial as a consequence of my earlier html5 audio API tutorial. In this tutorial, we will see how to control the audio with jQuery. This is handy if you are about to develop a dynamic application that makes use of several audio media and wants to control them from your jQuery script efficiently. Let’s start rolling!

How Far We Can Control?

multiple-audio-players

Well, we can control almost every feature that defaults HTML5 player provides, like play/pause/volume up/down, mute on/off etc 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.


Checkout The jQuery Audio Controller Demo

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 on 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 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 fairly easy to handle; you just 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 &gt;1){
        volume = 1;
    }
    $(".audioDemo").prop("volume",volume);
}

function volumeDown(){
    var volume = $(".audioDemo").prop("volume")-0.2;
    if(volume &lt;0){
        volume = 0;
    }
    $(".audioDemo").prop("volume",volume);
}Code language: JavaScript (javascript)

We need to keep checking whether the volume reaches its largest or minimum value. Otherwise, a JavaScript exception error will be thrown.

Mute On/Off:

We can instantly make audio off and turn it on to its earlier volume level easily with the use of “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 easily. If you are having any issues running any example or with the demo, please let me know by commenting here. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: audio, html5, javascript

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. newlandsvalley says

    August 2, 2013 at 11:02 am

    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?

    Reply
    • Md Ali Ahsan Rana says

      August 7, 2013 at 6:40 am

      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.

      Reply
      • newlandsvalley says

        August 7, 2013 at 7:13 am

        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.

        Reply
  2. C. Uy says

    January 19, 2014 at 7:28 am

    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!

    Reply
    • Md Ali Ahsan Rana says

      March 3, 2014 at 10:48 am

      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!

      Reply
  3. hariasblogger says

    May 21, 2014 at 3:04 am

    is there any option to only show muted control, please reply

    Reply
  4. AJ7 says

    September 20, 2014 at 1:47 am

    nice one , helped me a lot , thanks 🙂

    Reply
  5. abdulious3 says

    February 13, 2015 at 5:42 pm

    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?

    Reply
  6. anl says

    May 7, 2015 at 10:37 am

    Hi there, is there a way to exclude or deactivate the volume control from the standard html5 audio control.

    Reply
  7. Santosh says

    May 8, 2015 at 5:02 am

    im using multiple audio tags

    i want it to be played one at a time

    this is the code

    Reply
  8. Mohsin says

    January 14, 2016 at 1:43 pm

    aoa… dear how to play songs using this tag if we store path of song file in database

    Reply
  9. joe hart says

    February 12, 2016 at 11:36 pm

    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.

    Reply
  10. Israel says

    February 29, 2016 at 8:16 am

    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.

    Reply
  11. Fabio Andres Pino G says

    May 2, 2016 at 11:01 am

    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

    Reply
  12. Mike S says

    May 20, 2016 at 5:03 pm

    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?

    Reply
  13. Vijay says

    February 8, 2017 at 9:44 am

    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.

    Reply
    • treycranson says

      October 19, 2017 at 3:20 pm

      If you trigger the .load() method for that player, it should reset the audio.

      Reply
  14. tdings74 says

    November 10, 2018 at 6:53 am

    I am creating Rss Feeds [https://mySocialFeeds.com/] which I am importing into the audio app to play different songs / playlists. Works really well!

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Getting Started With Smarty Template Engine
    Getting Started With Smarty Template Engine
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Building Auth With JWT – Part 2
    Building Auth With JWT – Part 2
  • Beginning Codeigniter Application Development
    Beginning Codeigniter Application Development

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023