CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Programming Control HTML5 Audio With Jquery

Control HTML5 Audio With Jquery

Rana Ahsan June 23, 2013 18 Comments


 Control HTML5 Audio With Jquery    

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 make use of several audio media and want to control them from your jQuery script efficiently. Lets start rolling!

How Far We Can Control?

Well, we can control almost every feature that default HTML5 player provides like play/pause/volume up/down, mute on/off etc and additional functionality like stop,forward/backward capability etc.
multiple-audio-players
So, if you have N number of audio files on a single page, and instead of letting user dealing 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:

Lets 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>

We have kept two media, because of compatibility issue on browsers, so that alternative one 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 page load, neither the audio file nor any metadata. We will do them by ourselves from jQuery to boost the page load performance. Lets use the following code to load the audio:

$(".audioDemo").trigger('load');

We can also add event listener to know when its loaded. However, the event will be triggered immediate after the metadata loaded and 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");
    });

Play/Pause/Stop Audio:

Start playing audio and to pause it is fairly easy to handle, just need to trigger corresponding events as below:

//starts playing
$(".audioDemo").trigger('play');
//pause playing
$(".audioDemo").trigger('pause');

However, there is not ready event to stop an audio, so we will need to do it with help of ‘pause’ event and another property named “currentTime”, which indicates the current playing time. Here is what will do to stop:

function stopAudio(){
  //pause playing
  $(".audioDemo").trigger('pause');
  //set play time to 0
  $(".audioDemo").prop("currentTime",0);
}

Forward/Backward Capability:

Default HTML5 player doesn’t provide these 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);

Volume Up/Down:

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);
}

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

Mute On/Off:

We can instantly make an audio off and turn on to its earlier volume level easily with use of “muted” property. See the example code below, which actually toggle current mute state:

function toggleMuteAudio(){
    $(".audioDemo").prop("muted",!$(".audioDemo").prop("muted"));
}

Final Words:

Hope this small tutorial on controlling HTML5 audio with jQuery will help you develop audio/music driven web application easily. If you are having any issue on running any example or with the demo, please let me know by commenting here. Happy coding 🙂

Related

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

About Rana Ahsan

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

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.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • Generate HTTP Requests using c#
  • Facebook C# API Tutorials
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • LinQ To SQL Database Update Operations In C#
  • Utilizing Config File In C#.NET Application
  • Get Facebook C# Api Access Token
  • Getting Started With HTML5 Web Speech API

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • intolap on PHP HTML5 Video Streaming Tutorial
  • manishpanchal on PHP HTML5 Video Streaming Tutorial
  • Rana Ghosh on PHP HTML5 Video Streaming Tutorial
  • ld13 on Pipe Email To PHP And Parse Content
  • Daniel on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2021 · CodeSamplez.com ·

Copyright © 2021 · Streamline Pro Theme on Genesis Framework · WordPress · Log in