HTML5 Audio player with playlist

HTML5 Audio player with playlist

161 769505
HTML5 Audio player with playlist
HTML5 Audio player with playlist

HTML5 Audio player with playlist

HTML5 audio player. Many of you faced with the task of creating audio player at least once in your life. Quite often , you simply choose one of the available players, often it was the flash player. However, you may have already noticed, that these flash players do not work properly on mobile devices (iPhone / Android). Today I am going to tell you about how to create your own audio player (using HTML5 technology). This player consists of next elements: title, author, cover, basic controls (play / pause, rewind / forward) , two sliders (jQuery UI sliders): volume slider and and a song tracker, and even more: we will also have a playlist with a list of available songs.

Live Demo

[sociallocker]

download the sources

[/sociallocker]


I believe that you already know how to create a simple audio player using a standard <audio> element. In our example, we will not use a special markup for this elemet, we will create our own player with all the necessary controls. We will control the player using the event handlers of a created (in JavaScript) audio element.

Step 1. HTML

As usual, we have to include several files in the head section:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="author" content="Script Tutorials" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
    <title>HTML5 Audio player with playlist | Script Tutorials</title>
    <!-- add styles and scripts -->
    <link href="css/styles.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.8.21.custom.min.js"></script>
    <script type="text/javascript" src="js/main.js"></script>
</head>

And now, please have a look at our player’s markup:

<div class="player">
    <div class="pl"></div>
    <div class="title"></div>
    <div class="artist"></div>
    <div class="cover"></div>
    <div class="controls">
        <div class="play"></div>
        <div class="pause"></div>
        <div class="rew"></div>
        <div class="fwd"></div>
    </div>
    <div class="volume"></div>
    <div class="tracker"></div>
</div>
<ul class="playlist hidden">
    <li audiourl="01.mp3" cover="cover1.jpg" artist="Artist 1">01.mp3</li>
    <li audiourl="02.mp3" cover="cover2.jpg" artist="Artist 2">02.mp3</li>
    <li audiourl="03.mp3" cover="cover3.jpg" artist="Artist 3">03.mp3</li>
    <li audiourl="04.mp3" cover="cover4.jpg" artist="Artist 4">04.mp3</li>
    <li audiourl="05.mp3" cover="cover5.jpg" artist="Artist 5">05.mp3</li>
    <li audiourl="06.mp3" cover="cover6.jpg" artist="Artist 6">06.mp3</li>
    <li audiourl="07.mp3" cover="cover7.jpg" artist="Artist 7">07.mp3</li>
</ul>

Looks easy, does not it? As you can see – all the necessary elements are included here.

Step 2. CSS

The time has come to turn our bare HTML model into a beautiful player, for that, we need to define the styles used for each element.

css/styles.css

.example {
    margin: 50px auto 0;
    width: 400px;
}
.player {
    background: transparent url("../images/spr.png") no-repeat scroll center top;
    height: 162px;
    position: relative;
    width: 326px;
    z-index: 2;
}
.title, .artist {
    font-family: verdana;
    left: 167px;
    position: absolute;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}
.title {
    color: #FFFFFF;
    font-size: 14px;
    font-weight: bold;
    top: 23px;
}
.artist {
    color: #EEEEEE;
    font-size: 12px;
    top: 40px;
}
.pl {
    background: transparent url("../images/spr.png") no-repeat scroll -274px -175px;
    cursor: pointer;
    height: 34px;
    left: 270px;
    position: absolute;
    top: 20px;
    width: 32px;
}
.pl:hover {
    top: 21px;
}
.cover {
    background: transparent url(../data/cover1.jpg) no-repeat scroll center top;
    border-radius: 5px 5px 5px 5px;
    height: 94px;
    left: 20px;
    position: absolute;
    top: 20px;
    width: 94px;
}
.controls {
    cursor: pointer;
    height: 23px;
    left: 167px;
    position: absolute;
    top: 65px;
    width: 138px;
}
.controls .play, .controls .pause, .controls .rew, .controls .fwd {
    background: transparent url("../images/spr.png") no-repeat scroll 0 0;
    float: left;
    height: 100%;
    width: 33%;
}
.controls .play {
    background-position: -8px -171px;
}
.controls .pause {
    background-position: -8px -198px;
    display: none;
}
.controls .rew {
    background-position: -54px -171px;
}
.controls .fwd {
    background-position: -100px -171px;
}
.controls .play:hover {
    background-position: -8px -170px;
}
.controls .pause:hover {
    background-position: -8px -197px;
}
.controls .rew:hover {
    background-position: -54px -170px;
}
.controls .fwd:hover {
    background-position: -100px -170px;
}
.hidden {
    display: none;
}
.controls .visible {
    display: block;
}
.volume {
    height: 11px;
    left: 186px;
    position: absolute;
    top: 96px;
    width: 112px;
}
.tracker {
    height: 15px;
    left: 20px;
    position: absolute;
    top: 126px;
    width: 285px;
}
.ui-slider-range {
    background: transparent url("../images/spr.png") no-repeat scroll 5px -222px;
    height: 100%;
    position: absolute;
    top: 0;
}
.ui-slider-handle {
    cursor: pointer;
    height: 10px;
    margin-left: -5px;
    position: absolute;
    top: 2px;
    width: 10px;
    z-index: 2;
}
.volume .ui-slider-handle {
    background: url("../images/spr.png") no-repeat scroll -201px -188px rgba(0, 0, 0, 0);
    height: 13px;
    width: 13px;
}
.playlist {
    background-color: #333333;
    border-radius: 5px 5px 5px 5px;
    list-style-type: none;
    margin: -10px 0 0 2px;
    padding-bottom: 10px;
    padding-top: 15px;
    position: relative;
    width: 326px;
    z-index: 1;
}
.playlist li {
    color: #EEEEEE;
    cursor: pointer;
    margin: 0 0 5px 15px;
}
.playlist li.active {
    font-weight: bold;
}

Step 3. JavaScript

The beautiful player that does nothing – useless. To make it a true work of art, you have to fill it with events and functions. First at all, we need to initialize several variables:

js/main.js

    // inner variables
    var song;
    var tracker = $('.tracker');
    var volume = $('.volume');
    // initialization - first element in playlist
    initAudio($('.playlist li:first-child'));
    // set volume
    song.volume = 0.8;
    // initialize the volume slider
    volume.slider({
        range: 'min',
        min: 1,
        max: 100,
        value: 80,
        start: function(event,ui) {},
        slide: function(event, ui) {
            song.volume = ui.value / 100;
        },
        stop: function(event,ui) {},
    });
    // empty tracker slider
    tracker.slider({
        range: 'min',
        min: 0, max: 10,
        start: function(event,ui) {},
        slide: function(event, ui) {
            song.currentTime = ui.value;
        },
        stop: function(event,ui) {}
    });

Then, I prepared several general functions to handle with audio:

    function initAudio(elem) {
        var url = elem.attr('audiourl');
        var title = elem.text();
        var cover = elem.attr('cover');
        var artist = elem.attr('artist');
        $('.player .title').text(title);
        $('.player .artist').text(artist);
        $('.player .cover').css('background-image','url(data/' + cover+')');;
        song = new Audio('data/' + url);
        // timeupdate event listener
        song.addEventListener('timeupdate',function (){
            var curtime = parseInt(song.currentTime, 10);
            tracker.slider('value', curtime);
        });
        $('.playlist li').removeClass('active');
        elem.addClass('active');
    }
    function playAudio() {
        song.play();
        tracker.slider("option", "max", song.duration);
        $('.play').addClass('hidden');
        $('.pause').addClass('visible');
    }
    function stopAudio() {
        song.pause();
        $('.play').removeClass('hidden');
        $('.pause').removeClass('visible');
    }

And then I started to add event handlers to our control buttons. Play / Pause buttons:

    // play click
    $('.play').click(function (e) {
        e.preventDefault();
        playAudio();
    });
    // pause click
    $('.pause').click(function (e) {
        e.preventDefault();
        stopAudio();
    });

In order to turn to another song in the playlist, we have to stop playing a current song, pick a next (or previous) object in the playlist, and re-initialize our Audio element. Forward / Rewind buttons:

    // forward click
    $('.fwd').click(function (e) {
        e.preventDefault();
        stopAudio();
        var next = $('.playlist li.active').next();
        if (next.length == 0) {
            next = $('.playlist li:first-child');
        }
        initAudio(next);
    });
    // rewind click
    $('.rew').click(function (e) {
        e.preventDefault();
        stopAudio();
        var prev = $('.playlist li.active').prev();
        if (prev.length == 0) {
            prev = $('.playlist li:last-child');
        }
        initAudio(prev);
    });

Finally, few functions to handle with the playlist:

    // show playlist
    $('.pl').click(function (e) {
        e.preventDefault();
        $('.playlist').fadeIn(300);
    });
    // playlist elements - click
    $('.playlist li').click(function () {
        stopAudio();
        initAudio($(this));
    });

Step 4. Images

All used images are packed into one single sprite file: nav.png

HTML5 Audio player sprite image


Live Demo

Conclusion

That’s all for today, we have just prepared glorious audio player. Thanks for your patient attention, and if you really like what we done today – share it with all your friends in your social networks using the form below.

SIMILAR ARTICLES

Understanding Closures

0 24585

161 COMMENTS

      • Hello Andrey,

        I have 1000mp3 songs about 10GB I’ll like my audience to listen HTML5 Audio player with playlist if you can design for me and what is the cheapest web hosting you recommend and if you know monthly payment may be 10 friends my listen everyday through the website.

        Thanks

  1. Hi Mohamed,
    I think that this question is not for me, I don’t cooperate with 3rd-party hostings, I can’t judge about them. I think, that you should rely not only to the price, but and also to it’s stability

  2. I want to add auto play when click on playlist by add playaudio() function like this:
    // playlist elements – click
    $(‘.playlist li’).click(function () {
    stopAudio();
    initAudio($(this));
    playAudio();
    });

    but the tracker slider is not working. Is there any solution? Thank!

    • This is GREAT CODE. Thank you for developing it and making it available.

      I am having the same problem. The tracker function stopped working. I think it happened after I added the playAudio();

      // playlist elements – click
      $(‘.playlist li’).click(function () {
      stopAudio();
      initAudio($(this));
      playAudio();
      });

      Andrey, in a response, you said that there is code available. But I can not find it.

      Yes, sure, and it was already discussed earlier (with codes)

      Arthur

      • Hi Arthur,
        In general, this is jQuery UI bug discussed here: http://bugs.jqueryui.com/ticket/7477
        but you can try to avoid it, find the code:
        tracker.slider("option", "max", song.duration);
        and put the following right after it:
        tracker.slider("option", "value", tracker.slider("value"));

  3. Great code!

    But I think that this issue is something that needs to be addressed seriously and get it closed, since auto play on forward, backward and playlist buttons is a standard functionality that every player should have, and it’s a shame that this one doesn’t!

    The fallowing code is still not solving the problem:

    tracker.slider(“option”, “value”, tracker.slider(“value”));

    Please, spare some time and make this player, the best player online!

    Best,

    Obrad

  4. got the same issue here… andrey’s solution didn’t help.
    but the following will work:

    in your function:
    initAudio(elem) {

    find the following:
    song = new Audio(‘yourpath’ + url);

    and right afterwards add:
    song.addEventListener(“loadedmetadata”, function()
    {
    progress.slider(“option”, “max”, song.duration);
    });

    in your function playAudio
    remove progress.slider(“option”, “max”, song.duration);

  5. m.t.minded solution works for all browsers except Firefox?!

    In Firefox the slider finishes a lot before the track does?

    Any thoughts?

  6. Try to check syntax of the result JS code, you also can enable firebug to track the code – there might be an error in JS

  7. The code change doesn’t work for firefox to play song from clicking on playlist. Works fine in Chrome and IE and seem to get the time tracker but it finishes before song.

    Is there any solution to make it work in Firefox?

  8. Sorry my mistake it does work in firefox, my browser was cached so didn’t see it working it much later

  9. None of the above worked for me, however (tested using Chrome Version 40.0.2214.111 m) inside the function playAudio() {

    after song.play();
    //add code here
    song.addEventListener(‘loadedmetadata’, function()
    {
    tracker.slider(“option”, “max”, song.duration);
    });

  10. Thanks for your contribution, now the complete code to auto-play next songs looks like:
    song.addEventListener(‘ended’, function(){
      stopAudio();

      var next = $(‘.playlist li.active’).next();
      if (next.length == 0) {
          next = $(‘.playlist li:first-child’);
      }
      initAudio(next);

      playAudio();

      song.addEventListener(‘loadedmetadata’, function() {
        tracker.slider(‘option’, ‘max’, song.duration);
      });
    });

  11. Hi, I am spanish, so sorry for my english.

    I take your code, and it runs good, but I can’t listen nothing, in your live demo i can’t neither.

    Thanks

    • Hi Den,
      I haven’t implemented displaying timer and duration, but all these params are already available in the script (see- song.duration)

  12. hi all

    sorry but the live demo doesn’t work in firefox ?
    and i cannot play my music
    i have downloaded the sources and pasted them but …….but…..

    help ….
    thx
    cdom

  13. Great job, congratulations. I need your help to make the player start automatically without having to click the play. Can you help me I am layman in java.

  14. Hi Andrey,

    I downloaded and found it a very good player and easy to integrate. I am facing one 2 problems, please see below:

    1. Once a song finish, the player not automatically play the next song, we have to select and play from playlist. Same I have seen in Demo you created.

    2. Is there any possibility that we can set repeat and suffle option as well?

    Please do send me a message. Thanks

  15. I am working with this player and noticed that if I change the title of a song from 01.mp3 to what ever the real name of the song is that it somewhat covers the whole face of the player. is there a way to widen the player so long named songs will fit on the face of the player?

    Also, what do I need to do to make it auto play?

    • Hi Gary,
      We already discussed the auto play earlier – please read the comments before. With regards to the styles – they are here: styles.css

  16. Hello Andrey,

    After downloading the package I found three things I was wondering if you could help me out with. I see two have been addressed earlier in this forum, however I was unable to use any of the solutions provided as they did not work.
    1) I have lengthy songs in the playlist and many times the red scroll bar will come to the end of the bar, even though the song is not close to being over. Would there be any way to fix this?
    2) How would I make it so that the song transitions to the next one in the playlist automatically instead of having to click the next button?
    3) How would I implement auto play.

    Besides that, this code was perfect. Nice, compact, provides more than adequate info, and is easy to implement. Thank you so much for providing the code to it. I already have it up and running on my site

    • Hi Sarthak, the following code will help you organize an event for your second question:
      $("#player").bind(‘ended’, function(){
      // done playing
      alert("Player stopped");
      });
      Auto-play was already discussed earlier

      • Could you please explain this answer , where is the #player reference coming in , the code does not work as it is, what am I missing?

  17. If you access the #player (with jQuery) – you get an instance of this DOM element (div with id=player).

  18. I’ve tried this code $(“#player”).bind(‘ended’, function(){
    // done playing
    alert(“Player stopped”);
    });

    it should give me an alert when the track is finished, but does not, can you explain the code or modify I don’t see how it works

  19. That code I sent was of general purpose. Here is another version that is applicable for our script:
    song.addEventListener(‘ended’, function(){
    alert(‘Player stopped’);
    });
    That code can be placed directly below the first eventListener (timeupdate).

  20. hello, loved the design but as a beginner, well I know some programming but quite basic…
    the audioplayer with playlist does not work here . What I get: the image of the audioplayer, the buttons who roll, no red line, my coverimage 1 who appears, audio does not play … I did everthing you said, tried to put the mp3 files in folder “data” (like I did with cover 1, 2 etc) , then tried not in data, in data inclosed in audiofolder etc all does not work. Where to put the audio files? I also dowloaded from other sites the jquery-1.7.2.min.js and jquery-ui-1.8.21.custom.min.js and placed the scrips into the js folder… No success… well I tried to run then not in a site, just try to run in my safari… thx for help, hehe already searching hours on this…

  21. I can’t seem to get the player to play my mp3’s. They are all in a folder called: mp3 in the root of my website and the listing is: audiourl=”mp3/1000 Miles.mp3″

    Am I missing something? It looks great, just not playing the songs.

  22. great player. i love the design but i have a problem loading the mp3 files. it shows the playlist but it don’t play, no sound, it don’t show the cover/image too. i am using a chrome – windows 8. i uploaded all the files: css and js. please help! thank you!

  23. It is a good post, I just use tracker.slider(“option”, “value”, tracker.slider(“value”)); in line number 42. To use next and previous auto play just call the playAudio().

  24. hi andrey

    I’ve followed the above methods but why if when I’m clicking-play music, but the music does not run?? help me please, thanks

  25. Hello,
    I recently did your tutorial and the music player is showing up and everything but when I press play, the songs are not playing. I’m in the correct directory for my music files but I don’t understand why they’re not playing. Is there a certain path I need to use in order for the songs to play? Thanks!

    • Hi Penny, yes, all mp3 files should be in ‘data’ directory (covers should be in the same folder). Probably, there was an javascript error when you clicked the play button? Didn’t you notice any errors in browser’s console?

  26. Demo is working great. I downloaded the files and run index.html file. It is also working. I uploaded the code to my website. I can play and listen the audio. But

    1. the tracker slider is not moving when audio is playing
    2. volume tracker is not showing up.
    3. ‘Pause’ is not coming up when song is playing.

    Please help me to fix this. I don’t know about java code.

    Thank you

    • Hello Vamsi, didn’t you include jQuery (base) more than once on the page? It can be related to this problem. The code is not the java code, this is javascript code.

  27. Thanks a lot for this great piece of work!

    I studied the code of your audio player with sucess and added some parts of my own code to extend the behaivor.

    Simply the best HTML5 audio player available!

    Best regards ffrom germany :-)

  28. Andrey,
    I’m from Brazil and I’m trying create one playlist with auto-repeat and when one music ends other begins automatically.

    Do you can help me?
    Thanks bro

    • Hi Bruno, it can be done with the following event handler:
      song.addEventListener(‘ended’, function(){
      stopAudio();

      var next = $(‘.playlist li.active’).next();
      if (next.length == 0) {
      next = $(‘.playlist li:first-child’);
      }
      initAudio(next);

      playAudio();
      });

  29. Tracker is not working and sound is not working. Thanks for the start up though. I have to combine both your code and the native HTML5 audio control. Also, I made it dynamic to read the songs from the data folder.

  30. dear Andrew,
    that’s a GREAT player, thank you!!!

    what should I do to make a counter/timer visible (55:10) next to the slider?

    thank you so much for your help!
    regards, Miro

    • Hi Miro, in general, you need to create a new text element (div/span) to keep this song length, then, find ‘playAudio’ function, it already uses ‘song.duration’ value, so you need to convert it (it is in seconds) to mm:ss format. And then – put it into the prepared div/span element.

  31. Hi Andrew, Many thanks for the tutorial. Please how can I make the player(playlist) play from a different file sources or folders like the player on reverbnation or soundcloud main page. Once a song is uploaded, player can play from the root source.

    • Hi Charles, by default, the script takes mp3 from the ‘data’ directory. But you always can customize the code to allow another custom locations.

  32. How can one create a dynamic playlist that fetches song from the database and the users favorite to add to the playlist? Thanks.

  33. This tutorial is very helpful but please tell me how to add the autoplay fuctionatiality in this i.e. when one song finishes next song will play automatically please help.

  34. Hi,
    i am working for a charity welfare for those i have to put a playlist on there website.i am not a professional.so i just want to request you,that if you can,please make a simple format for the playlist in which i just have to add MP3.that can also play on auto play mode.i’ll be thankful.
    Have a nice day.bye

    • Hello Marry, frankly speaking, the format of as how it is presented by default is already simple format for the player with playlist. I suppose that you can use it as is. The autoplay was already explained in comments.

  35. Hi, and with dropbox’s music? I have so much songs in dropbox, and i like put an url in the audio player, but this is not run.. Help me Please..

    • Hi, what exactly dropbox do you mean? And, you don’t need to put urls into the player, better to use local music mp3 files.

  36. Okay first of all nice tutorial… great player

    I managed to build autoplay next song in it and it works thanks to the hero that replied in this tutorial but it isnt working on mobile devices.. on a mobile device it selects the next song it gives it the class active but it doesnt play the song.. does anyone know how to fixs this?

    Thanks in advance

Leave a Reply