Custom HTML Audio tag

There may be hundreds of Javascript and HTML  audio players available, but always the requirement will be somewhat different from the current one. So i felt it is better to learn customizing the audio player according to my own needs.
Let’s see how i could do it in a simple way,

Firstly I create an audio tag in my HTML page with a source tag which contains the link for the audio file.

Since i have not used the ‘controls’ Boolean in the tag it clearly says i don’t want the default audio player.

Now i create the audio player look and feel by using my own icons and html. See How i have created.

Before diving in to attaching the events to the custom audio player it is good to know the basic events and attributes of the audio tag.

Play() 

Plays the audio from the beginning or from the position where it was paused.

Pause()

Pauses the audio at the current playing position.

Stop()

Apparently there is no stop event in audio tag, but there is a way to achieve it. First pause the audio and set the currentTime of the audio to ‘zero’.

Volume Controller

An attribute to set the volume of the player, the value can vary from 0->1.

CurrentTime

Which gives the current position of the audio.

Duration

Which gives the duration of the audio file.

Once you know all this, you will will be able to understand what  i am doing in my script.
I have attached the id’s for the icons which I want to represent as the audio player to use them for click events, And i attach the click events on load of page using JQuery ready() function.

By here i was done with the basic functionality of the audio player, but i had to create a slider to give the user to move to a specific position.

Handling Silder

Then i created respective Html with a div containing of <hr> tag and the slider image.
To update the slider as and when the audio plays, we have to attach an event for ontimeupdate which calls the function for every millisecond or so.

To move the slider to a specific position, i just attached an onclick event to the container, inside that function I get the location of the clicked position and calculate the percentage of the song to be moved and set the currentTime to the calculated time.

Attaching the click event for the container in .ready() function.

And the function goes like this

PS:- Attach the Jquery.js if you’re copying my script.

Demo

Happy Coding…………………………,



Tagged as: