“It has been my observation that most people get ahead during the time that others waste.” --Henry Ford

How To: Create a Playlist for HTML5 Audio

Update: New article! - How To: Create a Dynamic Playlist for HTML5 Audio (Advanced)

Just a few years ago, if you wanted to add audio or video to your webpage, it wasn't as simple and easy as it is now using HTML5 and a modern browser. Lucky for us those days are long gone. You may already be familiar with the HTML5 ‘<audio>’ tag and how to use it to add an audio file to your webpage. For those who are not, here is a basic example:

  1. <audio controls="controls">
  2.     <source src="/song.mp3" type="audio/mp3" />
  3.     <source src="/song.ogg" type="audio/ogg" />
  4.     Your browser does not support the audio tag.
  5. </audio>
Code Sample 1.

And here is the above code in action:

That's great if you only have or want one song to play on your webpage, but what if you have a list of songs that you want to put on your page? You could use the ‘<audio>’ tag several times; one for each song. That takes up a lot of space on your page and causes a lot of overhead and will slow down your page because every song has to be loaded each time the page is displayed. This is frustrating for the end user browsing your site. So how do you solve this problem? By creating a playlist for the songs you want on your page.

Check out the HTML5 Audio Playlist example here.

The Code

Let's jump right in and get started with the code. We need to start with some html first. I am only going to cover what we need for the audio and playlist from the example.

  1. <div id="cwrap">
  2.     <div id="nowPlay">
  3.         <h3 id="npAction">Paused:</h3>
  4.         <div id="npTitle"></div>
  5.     </div>
  6.     <div id="audiowrap">
  7.         <div id="audio0">
  8.             <audio id="audio1" controls="controls" width="300">
  9.                 Your browser does not support the HTML5 Audio Tag.
  10.             </audio>
  11.         </div>
  12.         <div id="extraControls">
  13.             <button id="btnPrev" class="ctrlbtn">|&lt;&lt; Prev Track</button> <button id="btnNext" class="ctrlbtn">Next Track &gt;&gt;|</button>
  14.         </div>
  15.     </div>
  16.     <div id="plwrap">
  17.         <div class="plHead">
  18.             <div class="plHeadNum">Track</div>
  19.             <div class="plHeadTitle">Title</div>
  20.             <div class="plHeadLength">Length</div>
  21.         </div>
  22.         <ul id="plUL">
  23.             <li>
  24.                 <div class="plItem">
  25.                     <div class="plNum">1</div>
  26.                     <div class="plTitle">Happy Birthday Variation: In the style of Beethoven</div>
  27.                     <div class="plLength">0:55</div>
  28.                 </div>
  29.             </li>
  30.             <li>
  31.                 <div class="plItem">
  32.                     <div class="plNum">2</div>
  33.                     <div class="plTitle">Wedding March Variation 1</div>
  34.                     <div class="plLength">0:37</div>
  35.                 </div>
  36.             </li>
  37.             <li>
  38.                 <div class="plItem">
  39.                     <div class="plNum">3</div>
  40.                     <div class="plTitle">Happy Birthday Variation: In the style of Tango</div>
  41.                     <div class="plLength">1:05</div>
  42.                 </div>
  43.             </li>
  44.             <li>
  45.                 <div class="plItem">
  46.                     <div class="plNum">4</div>
  47.                     <div class="plTitle">Wedding March Variation 2</div>
  48.                     <div class="plLength">0:40</div>
  49.                 </div>
  50.             </li>
  51.             <li>
  52.                 <div class="plItem">
  53.                     <div class="plNum">5</div>
  54.                     <div class="plTitle">Random Classical</div>
  55.                     <div class="plLength">0:59</div>
  56.                 </div>
  57.             </li>
  58.         </ul>
  59.     </div>
  60. </div>
Code Sample 2.

Here is a brief explanation of the html code above:

  • Line 1: Starts the div wrapper for our audio controls and the playlist.
  • Line 2: Starts the Now Playing section.
  • Line 3: Used to display the action of the audio player (i.e. Paused, Now Playing).
  • Line 4: Used to display the title of the audio file that has been loaded.
  • Lines 6 - 11: The audio control.
  • Lines 12 - 14: Our playlist controls (previous and next buttons).
  • Lines 16 - 59: Defines the playlist. We use an unordered list item for each title of the playlist.

By itself, the html code doesn't do anything. It won't even play a single audio file because we did not include any ‘<source>’ tags to tell it which file(s) to load. We did that on purpose as you will see later.

To make this work we need to add some Javascript to the page. The example is written using jQuery. To start, we add the following lines of code just before the closing ‘</body>’ tag.

  1.         <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  2.         <script type="text/javascript">
  3.             jQuery(function($) {
  4.                 var supportsAudio = !!document.createElement('audio').canPlayType;
Code Sample 3.
  • Line 1: Add the jQuery library. (see the related articles for more information.)
  • Line 2: Start a script block.
  • Line 3: Start a jQuery script.
  • Line 4: Declares a variable named ‘supportsAudio’ and sets a boolean value to it.

With “!!document.createElement('audio').canPlayType;” we are checking whether or not the users browser supports the html5 ‘<audio>’ tag by creating a new audio element in the DOM (Document Object Model) and calling the ‘canPlayType’ method without any arguments. Because of this we have to use two exclamation points (!!) to get the correct boolean value. If we call it without any exclamation points we would get the following:

   document.createElement('audio').canPlayType: 
   function canPlayType() {
       [native code]
   }
That obviously is not a boolean (true/false) value.

With only one exclamation point we do get a boolean value. However, it is the opposite of what we are asking:
  !document.createElement('audio').canPlayType: false  <-(can not play audio file)

With two exclamation points we get the correct boolean value:
 !!document.createElement('audio').canPlayType: true  <-(can play audio file)

Okay, moving on with the next few lines of code:

  1.                 if(supportsAudio) {
  2.                     var index = 0,
  3.                     playing = false;
  4.                     mediaPath = '/how_to/assets/media/audio/',
  5.                     extension = '',
  6.                     tracks = [
  7.                         {"track":1,"name":"Happy Birthday Variation: In the style of Beethoven","length":"00:55","file":"01_Happy_Birthday_Variation_In_The"},
  8.                         {"track":2,"name":"Wedding March Variation 1","length":"00:37","file":"02_Wedding_March_1"},
  9.                         {"track":3,"name":"Happy Birthday Variation: In the style of Tango","length":"01:05","file":"03_Happy_Birthday_Variation_In_The"},
  10.                         {"track":4,"name":"Wedding March Variation 2","length":"00:40","file":"04_Wedding_March_2"},
  11.                         {"track":5,"name":"Random Classical","length":"00:59","file":"05_AFI_com"}
  12.                     ],
  13.                     trackCount = tracks.length,
  14.                     npAction = $('#npAction'),
  15.                     npTitle = $('#npTitle'),
Code Sample 4.
  • Line 5: Use the variable ‘supportsAudio’ in an if block.
  • Lines 6 - 10 and 17 - 19: Declare new variables.
  • Line 8: ‘mediaPath’ is the path to your audio files.
  • Lines 10 - 16: Declares a variable named ‘tracks’ and creates an array of JSON Objects.
  • Line 17: Get the number of elements in the ‘tracks’ array and assign the value to ‘trackCount’.
  • Lines 18 - 19: Creates a jQuery object of the DOM element and assigns it to the variable. This is similar to calling ‘document.getElementById("<id>")’ where “<id>” equals the html element id.

Moving on with more code.

  1.                     audio = $('#audio1').bind('play', function() {
  2.                         playing = true;
  3.                         npAction.text('Now Playing:');
  4.                     }).bind('pause', function() {
  5.                         playing = false;
  6.                         npAction.text('Paused:');
  7.                     }).bind('ended', function() {
  8.                         npAction.text('Paused:');
  9.                         if((index + 1) < trackCount) {
  10.                             index++;
  11.                             loadTrack(index);
  12.                             audio.play();
  13.                         } else {
  14.                             audio.pause();
  15.                             index = 0;
  16.                             loadTrack(index);
  17.                         }
  18.                     }).get(0),
Code Sample 5.

This section of code is the most important part of the playlist example so I will explain it in more detail.

Line 20:
audio = $('#audio1')
Set the variable ‘audio’ to the html element with the id of ‘audio1’. See Code Sample 2, line 8 above. HTML snippet: <audio id="audio1" controls="controls" width="300">
Line 20 (continued):
.bind('play', function() {
This is a jQuery way of assigning an event listener. In this case we want to do something when the media event ‘play’ is sent from the audio control.
Line 21:
playing = true;
Set the variable ‘playing’ to true because we are in the ‘play’ media event listener.
Line 22:
npAction.text('Now Playing:');
This is the jQuery way to set the text of the html element with the id of “npAction” (set on line 18 of Code Sample 4 above) to ‘Now Playing:’ because we are in the ‘play’ media event listener.
Lines 23 - 25:
The ‘})’, at the beginning of line 23, closes the ‘play’ event listener. We then chain the ‘paused’ media event listener just like we did the ‘play’ above, setting the variable and text appropriately.
Lines 26 - 36:
This is the magic code that makes a playlist possible. This creates the ‘ended’ media event listener. This event is triggered when the playing audio file reaches the end. This allows us to respond by loading the next track in the playlist or stop if that was the last file in the list. If the value of the variable ‘index’ plus 1 is less than the value of the variable ‘trackCount’, we increment the value of ‘index’, call the function ‘loadTrack’ passing ‘index’ as a parameter and call the audio control method ‘play()’ else we call the ‘pause()’ method, set ‘index’ to zero, and call the ‘loadTrack’ method with ‘index’ as a parameter.
Line 37:
}).get(0),
Close the ‘ended’ event listener and chain the jQuery method ‘get(0)’ to allow us access to the DOM node under the jQuery object. Without this we would be listening to the events from the jQuery object instead of the actual audio control.

Just a few more lines of code to go.

  1.                     btnPrev = $('#btnPrev').click(function() {
  2.                         if((index - 1) > -1) {
  3.                             index--;
  4.                             loadTrack(index);
  5.                             if(playing) {
  6.                                 audio.play();
  7.                             }
  8.                         } else {
  9.                             audio.pause();
  10.                             index = 0;
  11.                             loadTrack(index);
  12.                         }
  13.                     }),
  14.                     btnNext = $('#btnNext').click(function() {
  15.                         if((index + 1) < trackCount) {
  16.                             index++;
  17.                             loadTrack(index);
  18.                             if(playing) {
  19.                                 audio.play();
  20.                             }
  21.                         } else {
  22.                             audio.pause();
  23.                             index = 0;
  24.                             loadTrack(index);
  25.                         }
  26.                     }),
Code Sample 6.
  • Lines 38 - 63: Create the ‘click’ event listeners for the html buttons, Prev and Next Track (see Code Sample 2, lines 12 - 14 above). These event listners are similar to the media event listners abaove.

Almost there.

  1.                     li = $('#plUL li').click(function() {
  2.                         var id = parseInt($(this).index());
  3.                         if(id !== index) {
  4.                             playTrack(id);
  5.                         }
  6.                     }),
  7.                     loadTrack = function(id) {
  8.                         $('.plSel').removeClass('plSel');
  9.                         $('#plUL li:eq(' + id + ')').addClass('plSel');
  10.                         npTitle.text(tracks[id].name);
  11.                         index = id;
  12.                         audio.src = mediaPath + tracks[id].file + extension;
  13.                     },
  14.                     playTrack = function(id) {
  15.                         loadTrack(id);
  16.                         audio.play();
  17.                     };
  18.                     if(audio.canPlayType('audio/ogg')) {
  19.                         extension = '.ogg';
  20.                     }
  21.                     if(audio.canPlayType('audio/mpeg')) {
  22.                         extension = '.mp3';
  23.                     }
  24.                     loadTrack(index);
  25.                 }
  26.                 });
  27.             });
  28.         </script>
  29.     </body>
  30. </html>
Code Sample 7.
  • Lines 64 - 69: Create the ‘click’ event listener for any of the list items in the playlist.
  • Line 65: Declare a variable named ‘id’ and set the value to the index number of the list item clicked. The jQuery selector ‘$(this)’ is used to find which list item has been clicked and ‘.index()’ returns the zero-based index (number series starting with zero) of that item.
  • Lines 66 - 68: Check if the value of the variable ‘id’ does not equal the value of the variable ‘index’ then call the function ‘playTrack’ passing the variable ‘id’.
  • Lines 70 - 76: Create the ‘loadTrack’ function. This functions has one parameter: ‘id’.
  • Line 71: Remove the css class named ‘plSel’ from any element that has been asigned the class. The jQuery selector ‘$('.plSel')’ will select all elements that has the class name of ‘plSel’.
  • Line 72: Add the css class name ‘plSel’ to the list item identified by the parameter ‘id’. We do this with the special jQuery selector directive ‘:eq()’, but we need to pass the value of the parameter variable ‘id’ with it. To do this we concatenate the code by using the plus sign so the jQuery selector looks like this: ‘$('#plUL li:eq(' + id + ')')’.

That's it.

Check out the HTML5 Audio Playlist example here.