HTML5 Audio player with playlist

HTML5 Audio player with playlist

161 769510
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 24600

161 COMMENTS

  1. Nice work, but buggy
    Sometimes seek bar doesn’t progresses with song. on next click always have to click play button, after song ends next song doesn’t starts.
    On each new song, volume is max even though slider is on 0

    • Hi Niraj,
      Yes, this is true about the volume. In order to fix it, we will need to store the volume value in a new variable, for example:
      var dVol = 0.8;
      After, in the ‘initAudio’ function, right after the song initialization – we need to re-initialize volume too:
      song.volume = dVol;
      Finally, search for
      song.volume = ui.value / 100;
      and add the following code below it:
      dVol = ui.value / 100;

      • Excellent player, but can´t figure out where to put var dVol = 0.8; have tried all “logic ” options, any help would be appreciated! :-)

  2. Nice Tutuorial!
    But how can i do autoplay?
    I want to load the Page and then plays the music and not press the play button.

    nice regards

    flo

  3. i bought the html5 audio player with playlist and ive used iweb to make my website. but i dont know what to do now, i was told upload the player onto my server via filezilla and also upload my songs using mp3 and ogg but im stuck

  4. hands down the easiest to use player i have come across thus far, and looks great.
    however being a novice in this field i have a question rearding the music working without being covnerted to ogg media.
    is this an issue that any one has had, or no?

    • Hi Russ,
      We don’t use ogg files in the current tutorial. However, why it was told about the ‘ogg’ format, – basically because different browsers support different audio formats

  5. just add
    ================================================
    song.addEventListener(“ended”, function() {

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

    under song = new Audio(‘data/’ + url);

  6. I downloaded your demo and nothing happened (on Firefox 25.0.1 on a Mac). Is the demo not supposed to work out of the box? The same thing happens when I go to your live demo page. The graphics work, but no audio.

    • It should work in most of modern browsers (which support HTML5). Unfortunately, I can not reproduce your problem, because the demo works in all my browsers.

  7. Hi Andrew,

    how do we use a fallback solution, like ogg files? In the normal this is easy, but you have the mp3 files in a list. We need a fallback for Fiewfox and others who don’t play mp3. It’s probably easy, I just don’t see where to put it.

    Thanks,
    cardioid

    • Hi cardioid,
      There are few ways:
      1) to provide tracks with an extra param, for example: audiooggurl.
      2) you can substitute ‘mp3’ to ‘ogg’ in the ‘initAudio’ function

      After, you will need to determinate a browser, and it is of a certain type – work with OGG files instead of MP3

  8. i instantly needed to test if the volume control works on my old ipod touch… it did not work, i never was able to get this going …some1 got a suggestion ?

    • We use the ordinary jQuery UI slider to handle with volume. I believe that this control works good on iPod, however, I didn’t check it on iPod by the reason that I haven’t got this device.

  9. Nice mp3 player..but why is it stop after the first song?how can it be play the next song after the first

  10. Very nice player. Can you give an example of using the ‘playaudio();’ function to play all the songs in a playlist automatically?

    Also, is random shuffle possible?

    • Hi Andrew,
      The ‘playAudio’ function starts playing the active music file. In order to start playing music automatically, you can simulate pressing the first element of the playlist. Random shuffle is possible of course, but you will need to implement it yourself.

  11. Congratulation for your player

    In the same style than Jelson.

    How can I know when the track is finished with javascript ?

    At this time I could call the initAudio(next) function in order to play automaticaly the next track.

    Thanks you by advance.

  12. Very nice cool player.will you please advise me how play all audio mp3 listed one by one by auto play and where to insert any code for this.
    thanks

    • Hello Raghavendra,
      In order to play everything, you may follow the next logic:
      oninit – start playing the first element
      onended – start playing the next element (till the end)

    • Hi Gopi,
      In the current implementation, there is no repetition, you will have to implement it yourself.

    • Hi Dennis,
      Unfortunately I did not have jQuery 1.8.2 with me, however, I had jQuery version 1.10.2. I checked operability with this version – the player works fine.

  13. I really love the player…but i’m having a tough time implementing. I read your instructions on how to correct the volume/slider issue but may not be doing it correctly. Also, When i click the play button, i don’t see the Pause button. Any assistance would be greatly appreciated.

  14. Thank you so much!
    The player works and looks great in ALL major browsers
    and was very easy to set up.
    Good work!

  15. Hi Andrey,

    Great work in developing and publishing the code, good on you! Perhaps an alternative for non-coders is a new site I built – http://zoomclock.com.

    It’s web based so just requires a form to fill out and automatically creates the html 5 audio player.

  16. It needs work but not bad; when you click a track you still have to press the play button, it should automatically start the track when you click the title. The playlist should drop down from the beginning, it should not be hidden from the start but if you want to hide it you should be able to.

  17. Thanks for this excellent description. I need the player, once started, to play through each track on the playlist, either sequentially or indefinitely select random tracks, without having to start each new track after the current one has finished.

    Should be reliable on all devices, fixed, portable and mobile and with various browsers. Since HTML 5 is the new standard, I’m not sure Flash fallback is required, but it would be nice.

    Any thoughts on these couple issues?

    Thanks again..

    • Hi Ted, I suppose that you should know, that currently, the Flash is not supported on most mobile devices (this is disabled by default on Android, and this is completely not supported on iPhone). HTML5 is perfect solution.

  18. hell0 sir , i am new here , i have copied all the code but when i upload the page it display nothing ,

  19. I am rather new to HTML5 but I wanted a better player for my web site. This has been a great learning experience and thank you. I have the player going automatically to the next song and playing it. When I click on an item or click on forward or rewind, it automatically starts playing the music. My problem is that the tracker slider doesn’t go back to the initial zero state nor does it get updated from the timeupdate Listener. It also does not have a handle I can drag.

    I have to manually click on pause and then play buttons to get the slider to show the proper location in the song. Any thoughts on this?

    Here’s my current code (complete with commented out attempts and some debug code).

    /**
    *
    * HTML5 Audio player with playlist
    *
    * Licensed under the MIT license.
    * http://www.opensource.org/licenses/mit-license.php
    *
    * Copyright 2012, Script Tutorials
    * https://www.script-tutorials.com/
    */
    jQuery(document).ready(function() {

    // inner variables
    var song;
    var tracker = $(‘.tracker’);
    var volume = $(‘.volume’);
    var dVol = 0.5;

    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);
    song.volume = dVol;

    // tracker.slider(‘value’, 0);

    // timeupdate event listener
    song.addEventListener(‘timeupdate’,function (){
    var curtime = parseInt(song.currentTime, 10);
    document.getElementById(“debug”).innerHTML = curtime;
    tracker.slider(‘value’, curtime);
    });

    // end listener – play next
    song.addEventListener(‘ended’,function(){
    var next = $(‘.playlist li.active’).next();
    if (next.length == 0) {
    next = $(‘.playlist li:first-child’);
    stopAudio();
    initAudio(next);
    }

    //loadedmetadata
    // song.addEventListener(“loadedmetadata”, function() {
    // tracker.slider(‘value’,0);
    // });
    // meta data loaded

    // stopAudio();
    // initAudio(next);
    // playAudio();

    });

    $(‘.playlist li’).removeClass(‘active’);
    elem.addClass(‘active’);
    }
    function playAudio() {
    song.play();

    tracker.slider(“option”, “max”, song.duration);
    document.getElementById(“debug”).innerHTML = tracker.slider(‘value’);

    $(‘.play’).addClass(‘hidden’);
    $(‘.pause’).addClass(‘visible’);
    }
    function pauseAudio() {
    song.pause();
    document.getElementById(“debug”).innerHTML = tracker.slider(‘value’);

    $(‘.play’).removeClass(‘hidden’);
    $(‘.pause’).removeClass(‘visible’);
    }
    function stopAudio() {
    song.pause();
    document.getElementById(“debug”).innerHTML = tracker.slider(‘value’);

    }

    // play click
    $(‘.play’).click(function (e) {
    e.preventDefault();
    tracker.slider(‘value’,0);
    playAudio();
    });

    // pause click
    $(‘.pause’).click(function (e) {
    e.preventDefault();

    pauseAudio();
    });

    // 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);
    playAudio();
    });

    // 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);
    playAudio();
    });

    // show playlist
    $(‘.pl’).click(function (e) {
    e.preventDefault();

    $(‘.playlist’).fadeIn(300);
    });

    // playlist elements – click
    $(‘.playlist li’).click(function () {

    stopAudio();
    initAudio($(this));
    playAudio();
    });

    // initialization – first element in playlist
    initAudio($(‘.playlist li:first-child’));

    // set volume
    song.volume = 0.5;

    // initialize the volume slider
    volume.slider({
    range: ‘min’,
    min: 1,
    max: 100,
    value: 50,
    start: function(event,ui) {},
    slide: function(event, ui) {
    song.volume = ui.value / 100;
    dVol = ui.value / 100;
    },
    stop: function(event,ui) {},
    });

    // empty tracker slider
    tracker.slider({
    range: ‘min’,
    min: 0, max: 10,
    value: 0,
    start: function(event,ui) {},
    slide: function(event, ui) {
    song.currentTime = ui.value;
    },
    stop: function(event,ui) {}
    });
    });

      • Andry,

        Thanks for your reply. I regret that sent all of my code – that was a little over the top. I finally figured out some minor changes that allows this to work consistently. THe changes are shown below – for others who have no solved this yet…

        Now, I have another question. I have set this up so that, once a song completes, the next in the list starts. But it refuses to work for iphone/ipad. I have been reading that the Safari browser will not allow “autoplay”. Has anyone come up with a way to start a song after the previous one completed in Safari?

        in initAudio….

        // timeupdate event listener
        song.addEventListener(‘timeupdate’,function (){
        var curtime = parseInt((song.currentTime/song.duration)*100);
        tracker.slider(‘value’, curtime);

        }); // end timeupdate event listener

        change in playAudio()…

        function playAudio() {
        song.play();

        // tracker.slider(“option”, “max”, song.duration);

        $(‘.play’).addClass(‘hidden’);
        $(‘.pause’).addClass(‘visible’);

        change in track slider code….

        // empty tracker slider
        tracker.slider({
        range: ‘min’,
        min: 0, max: 100,
        value: 0,
        start: function(event,ui) {},
        slide: function(event, ui) {
        song.currentTime = (ui.value*song.duration)/100;
        },
        stop: function(event,ui) {}
        }); // empty tracker slider

  20. Hi, thank you very much for this simple player, works wonders for what I need. But here’s the problem:

    offline – works great, both chrome and firefox.
    I upload it, open the page online – everything works except it doesn’t show pause button, audio and track line. I tried position it differently, re-upload multiple times, changing the code, but nothing seems to work. Any kind of suggestion is appreciated.

  21. Ah, nevermind. Took a 15 min break, opened the document for the 165th time and just saw some strange script code at the bottom of my html. Deleted it and the player works perfect.

    Thanks anyway :))

  22. Hi,

    I’m trying to use this embedded within an app, but in iOS the progress bar seams to disappear. Wondered if anyone else had this problem and if there was a fix?

    Thanks

    Jake

1 2 3

Leave a Reply