Coding an audio player with jQuery and CSS
There are countless solutions out there for playing audio on your website. If you’re anything like me, however, none of them seem to look or function exactly how you would like them too. The solution, of course, is to code your own. With a little help from the jPlayer jQuery plug-in, you can create an audio player that is perfectly suited to your needs, whatever they may be.
NOTICE!
This code has been developed using a previous version of jPlayer. Due to a hectic schedule, we have not been able to update the code work properly with the latest version. Once projects slow down, we’ll be sure to get this article up to speed. Thankyou!
jPlayer
jPlayer is a plug-in for jQuery that allows you to design an audio player using standard html/CSS and then code it using JavaScript. Standard functions such as play and stop are simply a matter of feeding jPlayer the proper CSS ID’s. Additional functionality such as play lists is limited only by your imagination. jPlayer then takes care of everything else and even uses the HTML5 <audio> element and the OGG format for browsers that support them. Download jPlayer.
Our Goal
Before sitting down to design/code, it is always good to have a clear set of goals beforehand. It will save a lot of time and energy. These are our main goals
- Playlist functionality
- Upon track completion, next track plays
- Trigger song from anywhere on the page, not just within the player
- Show track load progress
- Show track play progress
View the demo of what we’re working towards
Writing HTML
The visual appearance of your player is pretty much up to you. The most important thing to remember is to give the various elements of your player unique ID’s. These ID’s will be used to assign the proper functionality to later. You can give the elements just about whatever ID you would like; however, jQuery by default looks for a standard set of ID’s I recommend using. I have used those ID’s in my code, because it will save us time coding later. Here is the code for our player:
<div id="jPlayer"></div><!-- Div that will contain the hidden flash or <audio> element //--> <div id="playerContainer"><!-- Main container of audio player //--> <ul id="playerControls"><!-- Player controlls, to be mapped to audio player functions //--> <li id="jplayer_prev">«</li> <li id="jplayer_play">Play</li> <li id="jplayer_pause">Pause</li> <li id="jplayer_stop">Stop</li> <li id="jplayer_next">»</li> </ul> <div id="playerProgress"><!-- Progess bars container //--> <div id="jplayer_load_bar"><!-- File load progress bar //--> <div id="jplayer_play_bar"></div><!-- Play progres bar //--> </div> </div> <div id="playerSongInfo">Artist - <em>Song Name</em></div><!-- Song Info //--> </div>
Most of this should be self-explanatory. One thing to note is that jPlayer will adjust the CSS width property of the progress bars from 0% to 100% as the song loads/plays.
CSS Styling
Once again, styling options are left completely open to you. In my player, I’ve used CSS to replace the text links with images I have located in the images subdirectory. jPlayer will take care of hiding any unneeded buttons, etc., so don’t worry about that. I included my CSS in the <head> section of my html, but you should probably keep yours in a separate CSS file.
<style type="text/css">
<!--
#playerContainer {
background-color: #f0f0f0;
width: 400px;
height: 74px;
padding: 8px;
border: 1px solid #d0d0d0;
}
#playerControls { list-style: none; padding: 0px; margin: 0px }
#playerControls li {
display: block;
width: 32px;
height: 32px;
float: left;
text-indent: -9999px;
cursor: pointer;
}
li#jplayer_play { background: url('images/control_play.png'); }
li#jplayer_pause { background: url('images/control_pause.png'); }
li#jplayer_stop { background: url('images/control_stop.png'); }
li#jplayer_prev { background: url('images/control_rewind.png'); }
li#jplayer_next { background: url('images/control_fastforward.png'); }
#playerProgress {
background-color: #ffffff;
height: 32px;
width: 256px;
float: left;
margin-left: 16px;
}
#jplayer_load_bar { background-color: #e0e0e0; height: 32px; width: 0%; }
#jplayer_play_bar { background-color: #1384bb; height: 32px; width: 0%; }
#playerSongInfo {
background-color: #e0e0e0;
height: 24px;
width: 390px;
padding: 4px;
margin-top: 8px;
float: left;
border: 1px solid #c0c0c0;
font-family: Arial, sans-serif;
font-size: 16px;
}
//-->
</style>
What we get is something that looks like this:

Writing the JavaScript with jQuery
Begin by including both jQuery and the jPlayer pluigin in your header like so:
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/jquery.jplayer.min.js"></script>
All of your code will go into the $(document).ready section. This is a jQuery convention that ensures that your code will not be run before the entire HTML document is ready. For more information, visit jQuery’s website. We’ll begin creating a variable to hold the current track number (starting with 0). Also, we’ll create an array of objects containing our play list info. Here, we are building this playlist by hand, but it is common to build the playList variable dynamically with PHP.
var currentTrack = 0;
var playList = [
{ title: "You Showed Me", artist: "Enoch Light and the Glittering Guitars", file: "http://localhost:8080/jPlayer%20Demo/mp3/enochlight_youshowedme.mp3" },
{ title: "I'm Gonna Love You...", artist: "Jimmy Smith", file: "http://localhost:8080/jPlayer%20Demo/mp3/jimmysmith_imgonna.mp3" }
];
Remember that empty div called #jPlayer we created? Now it’s time to let jPlayer know to use it for the audio player backend. We also set the initial options. There are a number that can be found within the jPlayer developer guide. The only one we are concerned with is ready which tells jPlayer what to do when it’s ready to roll. I’ve told it to call the playListChange() function that we will write later. I’ve also passed the function a value of 0, telling it to play the first track. Lastly, we’ll associate the play, pause, and stop buttons along with the progress bars. The commented code should be self-explanatory
$("#jPlayer").jPlayer({
ready: function() {
playListChange(0); // Play first song
},
oggSupport: false // We're using MP3s only in this example, so OGG support is not needed
})
.jPlayer('onSoundComplete', playListNext); // When a song ends, play call the playListNext() function we'll define
You’ll note that the previous and next buttons have not been associated. That is because jPlayer doesn’t handle play lists natively. We will have to write these functions ourselves.
$("#jplayer_prev").click(function() { playListPrev(); }); // Listen for Previous Track button click
$("#jplayer_next").click(function() { playListNext(); }); // Listen for Next Track button click
// Switch track
function playListChange(index) {
currentTrack = index;
$("#playerSongInfo").html(playList[currentTrack].artist + ' - <em>' + playList[currentTrack].title + '</em>');
$("#jPlayer").jPlayer('setFile', playList[currentTrack].file).jPlayer('play');
}
// Play next track. If already on last track, start back at the begining
function playListNext() {
var index = (currentTrack + 1 < playList.length) ? currentTrack + 1 : 0;
playListChange(index);
}
// Play previous track. If already on first track, start back at the end
function playListPrev() {
var index = (currentTrack - 1 >= 0) ? currentTrack - 1 : playList.length-1;
playListChange(index);
}
The last goal we need to achieve is the ability to trigger a song from anywhere on the page. For example, you may want to play a song when clicking on it’s name when it’s mentioned in a post. To do this we create a link and assign it a class of playSong. We then set the link’s rel attribute to the index (starting at 0) of the song we want to play. Here is an example of a properly-coded link that will play the first song in the playlist
<a class="playSong" rel="0" href="#">Play the first song</a>
And here is the JavaScript that makes it work
$(".playSong").click( function() {
index = parseInt($(this).attr('rel'));
playListChange(index);
}); // Change to track defined by rel of link with playSong class
For simplicity’s sake, here is the entire JavaScript code
$(document).ready(function(){
var currentTrack = 0;
var playList = [
{ title: "You Showed Me", artist: "Enoch Light and the Glittering Guitars", file: "http://soulsizzle.com/demos/jPlayer/mp3/enochlight_youshowedme.mp3" },
{ title: "I'm Gonna Love You...", artist: "Jimmy Smith", file: "http://soulsizzle.com/demos/jPlayer/mp3/jimmysmith_imgonna.mp3" }
];
$("#jPlayer").jPlayer({
ready: function() {
playListChange(0); // Play first song
},
oggSupport: false
})
.jPlayer('onSoundComplete', playListNext);
$("#jplayer_prev").click(function() { playListPrev(); }); // Listen for Previous Track button click
$("#jplayer_next").click(function() { playListNext(); }); // Listen for Next Track button click
$(".playSong").click( function() {
index = parseInt($(this).attr('rel'));
playListChange(index);
}); // Change to track defined by rel of link with playSong class
// Switch track
function playListChange(index) {
currentTrack = index;
$("#playerSongInfo").html(playList[currentTrack].artist + ' - <em>' + playList[currentTrack].title + '</em>');
$("#jPlayer").jPlayer('setFile', playList[currentTrack].file).jPlayer('play');
}
// Play next track. If already on last track, start back at the begining
function playListNext() {
var index = (currentTrack + 1 < playList.length) ? currentTrack + 1 : 0;
playListChange(index);
}
// Play previous track. If already on first track, start back at the end
function playListPrev() {
var index = (currentTrack - 1 >= 0) ? currentTrack - 1 : playList.length-1;
playListChange(index);
}
});
You’re JavaScript audio player should now be fully functional. The play and pause buttons will hide and unhide as necessary, and the progress bar can be clicked in order to jump to another position in the song.

This is just a basic idea on how you can use the jPlayer plugin. I suggest you spend some time with the latest version of the developer guide, and in the future I might expand this post to cover keeping track of time and other tricks.
40 Comments
Leave a Reply
About
Welcome to the blog of Ryan Marganti, the owner of SoulSizzle Design. I am currently booked until the end of time and not accepting freelance work. Contact me with any questions or comments.
Categories
Recent Posts
-
Create an Ajax Sorter for WordPress Custom Post Types
Create an AJAX sorter for WordPress custom post types
-
Adding Additional Image Sizes to WordPress Themes
Define and implement Wordpress images resolutions beyond the default Large, Medium, and Thumb sizes.
-
Manage a Boatload of WordPress Sidebars With Help From jQuery
Enhance the Wordpress dashboard with jQuery
-
Display a Different Number of Posts in WordPress Searches
Change the number of results shown in a Wordpress search
No public Twitter messages.
Social comments and analytics for this post…
This post was mentioned on Twitter by jQuery_Tips: Coding an audio player with jQuery and CSS http://bit.ly/5labqS…
Awesome! Thanks!
looks great ! where is the Demo page ? you should link to Demo page too …
@saurabh shah,
A link to the demo is now up. Thanks for the advice.
I’m having problems with the player controls. Even when I add my own images I am getting some character encoding problems where the images should be. E.g. The buttons display ?0BB ?020… even when the Divs are empty :S I am trying to roll it out in wordpress… Any ideas?
noshatter,
The negative text indents should be hiding any text, even if there are encoding problems. The fact that you are having issues even in the empty divs is perhaps what is most confusing. Are you simply copy and pasting some of my code or are you retyping what is necessary? Anything I’ve provided should be UTF-8 encoded. Does this match the encoding of your function.php and style.css theme files? WordPress generally uses UTF-8 encoding, but I’m not sure where else the issue could lie.
Thanks for your reply soulsizzle. I have just been playing around with it, and it turns out that the elements were causing the problem. I have no idea why this is happening, as html elements are an in-built feature of wordpress. Perhaps it’s my host that’s causing the problem… Great tutorial anyway. It’s the only decent alternative example I have been able to find. Keep up the good work,
nonshatter x
the “” elements
Oops, code posting is disabled! **the html li tags**
How can I disable autoplay when the page loads?
@Peter,
With the code above, jPlayer calls playListChange(0) once the player is ready. playListChange() changes the track and plays it. We will modify playListChange() to change the track as before. However, if a second parameter is passed as ‘false’, it will not actually play the song.
You can makes this happen by making these changes to the playListChange() function.
// Switch track function playListChange(index, play) { if (play == null) play = true; currentTrack = index; $("#playerSongInfo").html(playList[currentTrack].artist + ' - <em>' + playList[currentTrack].title + '</em>'); $("#jPlayer").jPlayer('setFile', playList[currentTrack].file); if (play == true) $("#jPlayer").jPlayer('play') }Then, change the function call located in the jPlayer “ready” function to the following.
Your player will now queue up the first track, but won’t play it until you hit the play button.
Great, thanks! I actually found a solution by adding a line of code to the ready function, but your solution is cleaner. Here’s what I did:
Old code:
$(“#jPlayer”).jPlayer({
ready: function() {
playListChange(0); // Play first song
},
oggSupport: false
})
New code:
$(“#jPlayer”).jPlayer({
ready: function() {
playListChange(0); // Play first song
$(“#jPlayer”).jPlayer(‘setFile’, playList[currentTrack].file).jPlayer(‘stop’);
},
oggSupport: false
})
Hi. Just found this and I think it may be my best option for my WordPress blog – however, can you give any advice on how to cope with multiple instances on a page?
As you can see from my site, I have one (currently Flash) player per post and of course multiple posts per page.
Hi, thanks for your updated script, it’s the only one I found that will work on all important browers + Android + iPad. Great!! One question though: how do you call the play time function? I mean:
var jpPlayTime = $(“#jplayer_play_time”);
var jpTotalTime = $(“#jplayer_total_time”);
This doesn’t work. Thanks for letting me know.
Great tutorial!
I am the dev of jPlayer and will take note of the MP3 only for Android.
Some of your links point to the old 0.2.5 dev guide. This text here:
“There are a number that can be found within the jPlayer developer guide. ”
Take note of that incorrect URL though… Because you are using the temporary links to the jPlayer dev guide in other places. The /latest/ is being replaced with /1.2.0/ at the server.
A perma-link to jPlayer 1.2.0 guide is:
http://www.happyworm.com/jquery/jplayer/1.2.0/developer-guide.htm
I raise this since within the week jPlayer 2 is coming out and your links will point to the new dev guide. (Apart from the one that points to the old 0.2.5 guide.) jPlayer 2 has some control code changes from jPlayer 1.
Best regards,
Mark P.
Lead Developer of jPlayer.
@Mark P
Thanks for pointing out the incorrect links. As I’ve updated this guide, looks like the links were missed. I’ve changed them to point to v1.2.0, aside from the last which will continue to point to the latest version. I have changed its wording, however.
Thank you for this tutorial! I have been having SO many problems trying to customize jplayer its unreal.
I have your tutorial working on my site..BUT..it only works in Chrome! Can you maybe take a minute to look over my code?
http://www.solid54.com/clients/montageworld/
Any help would be greatly appreciated!
Thanks!
Phil
jPlayer 2 has been released which supports both video and audio. This tutorial relates to jPlayer 1, which is still available on our website.
jPlayer has a new home at:
http://www.jplayer.org/
@soulsizzle: We changed the URL system, removing the .htm from all URLs and replacing with a slash. For example:
http://www.jplayer.org/1.2.0/developer-guide/
The old URLs will work, they redirect to the new site.
@Phil: As you know, your problem has been solved on the jPlayer Google Group, which is the best place to ask for support:
http://groups.google.com/group/jplayer
The demo page at
http://soulsizzle.com/demos/jPlayer/index.html
returns 404
Hello,
Thank you for your tutorial.
On my personnal page, i include your code.
I changed a few things, but with or without my changes, music doesn’t work !
I can change song with previous or next button.
Title of the current song change, but there is no sound.
I think it’s a code’s problem, because with the different demo from http://www.jplayer.org/ , song work !
I take your code because with the code of http://www.jplayer.org I do not have the title of the current song.
have you got any ideas ?
Best regards,
Dalto
Hello,
I found my problem, but the last problem that i have, it’s Firefox and IE.
Player only works with Chrome.
Have you got any ideas ?
Best regards,
Dalto
nice tutorial. thank you
Hello, i found my problem (problem of the swf file => not the good version for the version of the js).
Very nice tutorial and very nice player
thank you for this nice tutorial.
what happened to the demo?
[...] way for severe infections of bone (osteomyelitis) or heart valves (endocarditis). adipex zoloft adipex retard.hu weight loss results with adipex coupons for adipex adipex headaches adipex refill diet drugs forums [...]
excellent tutorial, wish I had found it sooner
Create your LONG URL!! with our easy to follow instructions, we have the greatest bunch of url/domain scripts on the web.
Hi, I am using this script for a continuous playlist. Question: how can I make this playlist shuffle? No shuffle button, just auto-shuffle. And is there a way to make it repeat? Thanks!
[...] Marijuana |http://ow.ly/1u1k8S # 2011/06/23 Webdesign and content © 2011 SoulSizzle Design Back to top ^ GA_googleAddAttr("AdOpt", "1"); GA_googleAddAttr("Origin", "other"); [...]
I am quite good in writing medical articles as well
fairly refreshing. Having said that, I appologize, because I do not subscribe to your entire theory, all be it refreshing none the less. It looks to us that your commentary are not totally rationalized and in actuality you are generally yourself not even entirely convinced of the assertion. In any event I did appreciate looking at it.
Is there any way to get a music player on a site that won’t allow Javascript for security reasons? (ie: Lefora)
Exceedingly insightful appreciate it, I presume your trusty visitors may perhaps want way more well written articles along these lines maintain the good content.
Particularly educative bless you, I’m sure your trusty audience would certainly want more writing such as this carry on the great content.
Hi,
I hav play button on my page , when i click on that play button i want to play song directly, so i used the above code but it is not playing any song , is it because of IE issue?
Prompt response will be appreciated
where can i get the “png” image file ?
Hi, nice article, thanks! Demo page redirect to 404 page. You can fix this?
i’m trying to implement this player in a personal webapp for ios , i’m using IOS 5.1 everything is working fine excep the play button , stop and pause button . fast forward and rewind load the song but the songs are not playing , i relatively new with jquery .can somebody help me figure out what i did wrong .and i would like some pointers about how to do the playlist dynamically. thank you
Great tutorial but the demo link is not working.
Thanks Soulsizzle for this tutorial, it is out of date but was very useful.
I adapted this solution to new jplyer api and my needs, I expect this be useful for community.
Follow the code working:
http://jsfiddle.net/2CsH4/