DEV Community

Cover image for Creating web music player in Howler.js and JQuery
Jahongir Sobirov
Jahongir Sobirov

Posted on

Creating web music player in Howler.js and JQuery

Today we will learn with you how to create a simple music player in Howler.js and JQuery libraries. I recommend howler.js if you want to put a song on your website. Let's get to work! We can write these codes in our HTML file:

<!DOCTYPE html>
<html>
    <head>
        <title>Web Music Player</title>
        <script src="https://unpkg.com/howler@2.2.3/dist/howler.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    </head>
    <body>
        <script src="./sound.js"></script>
        <button id="play">Play</button> <!--Play button-->
        <button id="pause">Pause</button> <!--Pause button-->
        <button id="voladd">Vol+</button> <!--Add volume button-->
        <button id="volmin">Vol-</button> <!--SUbtract volume button-->
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

In Howler.js we write the song file and the volume:

var howler = new Howl({
   src: ['./auf.mp3'], // file name
   volume: 0.5 // volue
});
Enter fullscreen mode Exit fullscreen mode

We will add functions in JQuery to the keys written in our HTML file above.

$(document).ready(function(){

   $("#play").on("click", function(){}); // this function for play button
   $("#pause").on("click", function(){}); // this function for pause button
   $("#voladd").on("click", function(){}); // this function for add volume button
   $("#volmin").on("click", function(){}); // this function for subtract volume button

});
Enter fullscreen mode Exit fullscreen mode

Now we will combine the code written in Howler.js into our file where these JQuery codes are written and attach several methods of Howler.js to the functions written in JQuery for our music player.

$(document).ready(function(){

   var howler = new Howl({
      src: ['./auf.mp3'], 
      volume: 0.5 
   });

   $("#play").on("click", function(){
      howler.play(); // this method for playing music
   });

   $("#pause").on("click", function(){
      howler.pause(); // this method for pause music
   }); 

   $("#voladd").on("click", function(){
      var vol = howler.volume(); // this method get currently volume music
      vol += 0.1; // adding volume
      if(vol > 1){
         vol = 1; // If the volume is greater than 1, it is equal to 1
      }
      howler.volume(vol) // This method determines the volume
   }); 

   $("#volmin").on("click", function(){
            var vol = howler.volume(); // this method get currently volume music
      vol -= 0.1; // subtracting volume
      if(vol < 0){
         vol = 1; // If the volume is smaller than 0, it is equal to 0
      }
      howler.volume(vol) // This method determines the volume
   }); 

});
Enter fullscreen mode Exit fullscreen mode

You can see the results on github. I hope you enjoyed this article.

Discussion (0)