How to: build a responsive audio player with HTML5, SASS and JS — Part 2

Over the past few months we have been working with Hertfordshire County Council and the great team at the MusicNet East Musical Inclusion Project to create a website for young aspiring musicians in the South East of England.

Songwriter is a community of aspiring musicians that submit songs to the chart, which ranks the songs based on Weekly Listens. As part of that project we built a responsive audio player using HTML5, SASS and JS. With modern web technologies this task was much more simple than you might expect, so we wanted to share the process for anyone who might want to build their own!

You can see the full project here or read more about it on our project page.


THE START

Once you have all your HTML & SASS in place, it’s time to work on functionality (Check part 1 of this blog to make sure you have all right code in place).
To start lets put in the audio tag that we are going to control and populate it with an audio file. Add the following before the controls.

<!-- The Audio -->
<audio id="audio" src="song.mp3"></audio>

and make sure you have an audio file in the root directory and name it ‘song.mp3’ or make sure you have the correct filename in your audio src.


PLAYING & PAUSING

The first thing we are going to code is the ability to play the song and then pause it. Let’s set a few things up first.
Set a variable to grab the audio player we are going to be manipulating by its ID using the following:

var player = document.getElementById('audio');

Now we need to add in a function for when the play button is clicked:

$(document).on('click', '.play', function(e) {
});

Now using the player variable we set up we can tell the audio tag to start playing the src audio file with one simple bit of code:

player.play();

Put that inside the click function and now clicking on the play button will start the song playing. The next step is to change the play button to a pause button. We can use jquery to hide and show them with these two lines:

$( ".play" ).hide();
$( ".pause" ).show();

Your function should now look like this:

$(document).on('click', '.play', function() {
player.play();
$( ".play" ).hide();
$( ".pause" ).show();
});

And we can repeat that bottom section to add in a function to pause the music by changing player.play(); to player.pause(); and switching which element to hide and which to show

Your script should now look like this:

var player = document.getElementById('audio'); //Get audio player
$(document).on('click', '.play', function() { //Play on click
player.play();
$( ".play" ).hide();
$( ".pause" ).show();
});
$(document).on('click', '.pause', function() { //Pause on click
player.pause();
$( ".pause" ).hide();
$( ".play" ).show();
});

This can be done in many different ways but for this example, you can easily see exactly what’s going on.


THE PROGRESS BAR

The next part we are going to build is the progress bar. To start we need to set an event listener on the player that will trigger a function when time has changed on the player. To do this we use the addEventListener method which takes 2 parameters we need. The first is a string representing the event type to listen for and the second is the object that receives a notification. This should look like the following:

player.addEventListener("timeupdate", updateProgress);

player is the audio player we defined. addEventListener is the function we are using on the audio player and our 2 arguments are; timeupdate (what we are listening for), updateProgress (the function we want to trigger).

Now we need to build the function updateProgress(). To start, declare the function with the following:

function updateProgress() {
}

We now need to set two variables, one for the progress bar that we are going to be manipulating and one for the width of the progress bar as a %. Add the following into the updateProgress() function.

var progress = $(".progress"); //The progress bar
var value = 0; //Song position starts at 0

Now we need to check if the songs duration has been set to Infinite or not so that on Infinite length songs the bar is just 100% all the time and if not, is the song past 0:00. We do this with the following:

if(player.duration == 'Infinity') { //Song is infinate in length
value = 100;
} else if(player.currentTime > 0){ //Songs current time is past 0

}

If the song is past 0:00 we want to start moving the progress bar. To know the percentage of how wide the progress bar needs to be we need to do some maths:

value = Math.floor((100 / player.duration) * player.currentTime);

This maths gives us the percentage out of 100 that the song is through its playthrough and stores it in the value variable.

The last part we need to do is set up is the actual animation and change of the progress bar using the value we now have as the percentage. We do that with the following code after the closed if statement:

progress.stop().animate({'width':value + '%'},500);

This animates the width’s percentage for the duration of 500 milliseconds.


THE TIME STAMP

Next, we are going to update the time stamp as the song is being played. Firstly we need to make a function that changes the format of the of the time into the format we need. The function look like this:

function formatTime(time) { //Change time format
minutes = Math.floor(time / 60);
minutes = (minutes >= 10) ? minutes : "" + minutes;
seconds = Math.floor(time % 60);
seconds = (time >= 10) ? seconds : "0" + seconds;
return minutes + ":" + seconds;
}

This function takes a time we give it (from the player) and convert’s the format into a timestamp. The last thing for us to do after this is output the timestamp onto the player. Inside the updateProgress function add in the following which will add the timestamps to the player:

$('#music-player #time').html(formatTime(player.currentTime)); //Set the new timestamp
$('#music-player #total-time').html(formatTime(player.duration)); //Set total timestamp

FINAL CODE

You should now have a working HTML5/JS audio player that has a pause/play button and a progress bar with time stamps! To download a working version of this code click HERE.


Originally published at www.eighty8design.co.uk on November 25, 2016.