Figure 1.2

In this article we will be making an mp3 player from scratch, using the most basic pieces:

  • Basic text editor
  • Up to date browser (Chrome, Firefox, Internet Explorer, Opera, Safari….)
  • jQuery 1.12.3 uncompressed developer edition (https://jquery.com/download/)
  • Languages: HTML5 and JavaScript
  • Data: several or more songs in .mp3 file format

This article takes for granted that you have at-least a cursory understanding of html, javascript, css, and basic programming, as everything will not be spelled out and should be intuitive for someone with the most basic skill-level of coding techniques. Hopefully, you have at-least read an introductory guide

.

I am very hopeful that the list of items above are at your disposal; at the very least, you probably have four out of the five, except, perhaps, the third bullet item (download jQuery). Why don’t you get that now, before proceeding…

Provided that the requirement for the second bullet item is met, which I can’t imagine it not being if you use the internet on a regular basis, our consolidation of pieces is now complete, and we should be all set to start organizing. But before we do that, let’s look at a precursor to the technology we plan to use to unravel the steps we need to take, as to gain a better understanding of the what, why, and how.

In a time not so foregone, developing a music player and streaming audio from a web browser (pc or mobile device) was an arduous task. One that required the use of an agonizingly slow, increasingly antiquated, resource hungry, and security vulnerable application like Adobe Flash, or earlier aliases Macromedia Flash and Shockwave. Let me see, did I forget any characteristics of this green eyed monster, oh yeah, soon to be defunct! For those who have not heard of Flash, good for you. However, it is a software platform used to create multimedia applications (audio, video, etc.), scaling cross-platform hardware/software applications and devices. Unfortunately, it can still be found roaming in double-u (www) land, occasionally, by website provocateurs adverse to change. Maybe they are just transitioning away from flash slowly, who knows; let’s give them the benefit of the doubt. At any rate, the call to retire Flash is a movement that is picking up speed, and actively recruiting, or shall I say encouraging developers to kill that flash, the use of it that is … (http://occupyflash.org/).

This brings us to facilitating our streaming musical endeavor, using, drum rolls please, HTML5 (cheers, bells, whistles ring out until a low rumble). The 5th iteration, obviously, of the HTML standard. The iteration that gives strong support (via API and DOM) and implementation to multimedia and graphical content. HTML5 gives us the meat without all of the fat, like that which Flash provides. To be clear, HTML5, unlike flash, does not play audio and video within a webpage natively, but rather uses JavaScript or CSS to accomplish this feature. This is not a con, but definitely a pro. For this characteristic affords HTML5 to offer better security, use significantly less system resources, and reduced execution and implementation.

Now, let’s plan how we want to bring our pieces together to create a collage of musicality. And to start, we will look at a visual representation of our finished product:

Figure 1.0

Figure 1.0 Basic MP3 Player made with HTML5 and Javascript

So, having a visual representation of what our player will look like or some variant thereof (depending or your styling taste), the first thing we need that probably comes to mind is … what? You guessed it, we need a UI (user interface). And that can easily be accomplished with HTML5 and CSS. Secondly, you probably considered that we need to have access to our data (mp3 files), again HTML5 will allow us this access. And lastly, I’m sure you were thinking this already, we need to have some type of logic to help us visualize and control our data (mp3 files). This is where our JavaScript and JavaScript library (jQuery) will come in handy. Now, let’s specify some key pieces we will need to finish our puzzle:

HTML5

  • <audio> tag which we will make use to access our audio files.
  • <div> tag which we will make use to design our UI.
  • <span> tag which we will make use to display playlist audio current time/total time.
  • <ul> and <li> tag to create and display our audio playlist.

CSS

  • We use css to make our html presentation satisfactory to our cosmetic tastes.

JavaScript/jQuery

  • JavaScript allows us to give action to our mp3 player by creating events for the controls of our player.

Having somewhat of a map of how certain tools are used in our project, let’s consider some other important factors as trudge along.

Mime Types

These are nothing more but descriptions of the file types your system will use to play audio (mpeg, mp4, ogg, and wav). If the mp3 application is being launched on a server then the web server’s .htaccess file will need to be configured to accommodate the file type(s) to be used. For a local copy of the mp3 application, these types can be configured in the HTML5 <audio> tag, which we will cover in the next session.

Audio File Type – Extensions Mime Type
MP3 audio/mpeg
MP4/AAC audio/mp4
OGA/OGG audio/ogg
WAV audio/wav
Figure 1.1

Figure 1.1 File extensions and accompanying Mime Types

HTML Audio Browser Support

Browser support is another consideration. Certain browser handle all audio codecs, and others handle only a few. So, ensuring that you choose multiple audio file types to accommodate support lacking browsers is crucial. According to www.w3school.com, the chart below outlines the current browser support:

Figure 1.2

Figure 1.2 Audio Browser Support


The way we accommodate for non-browser support (eg. Internet Explorer) using the <audio> tag in HTML5 is like so:

HTML5 Audio tag

The code above simply adds an audio source file in two different formats (.ogg and .mp3), and then specifies the Mime type for our system (audio/ogg, audio/mpeg). And just to cover another type not listed, a wav file would have the following Mime type (audio/wav), as pointed out in Figure 1.1. The last line is used alert the user that their browser does not support file type(s).

Media Events

Various events that are invoked when managing media in our HTML environment. This refers to the action that directly occurs within our application: selecting the play button, pause button, next/previous button, volume control, current time, duration, etc… We can assign handlers to these events, enabling us to trigger an event or eventListener at will, waiting for some action to occur (eg. audio track finish playing).

In the context of our project, a handler is our JavaScript code (as a function) not added inside the <script> tags, but rather, inside the html tags, that executes JavaScript to make something happen, such as pressing a button, moving your mouse over a link, submitting a form etc. The syntax for event handlers looks like the following or some variant:

name_of_handler=”JavaScript function”

Similarly, an eventListener causes some action to occur. However, it does not have to be instantiated inside our HTML. It can be invoked inside our <script> tag or JavaScript file, whatever we choose to use.

As an example, let’s consider a gated community, where a card containing an RFID (Radio Frequency Identification) chip is used to gain access to that neighborhood, via the gate. The chip in the card holds the instructions, or handler if you will, that triggers the gate to open. But, the gate will not open until the person with the card presents it to the gate’s reader. Think of the card as the event attribute, the instructions on the chip as the handler (code), and the reader as an object (button). Now, in the context of creating our mp3 player we will need an object (play/stop button, etc.), an event attribute (media event), and a handler (code instructions), actually several objects and handlers, but you get the gist…. We can trigger some action when a user interacts with one of our objects (play/stop button), linked to a handler, to produce a desired action. Easy, right?

Here are the media events (attributes) of our audio element that we will use:

  • ended – Sent when playback completes
  • pause –Sent when playback is paused
  • playing –Sent when playback of the media starts (for the first time)
  • play – Sent when playback starts after having been paused
  • timeupdate – The time indicated by the element’s currentTime attribute
  • volumechange – Sent when the audio volume changes

Note: some events above are included in the default controls (play button, volume), and may not be apparent in our included code.

Audio Streaming

Audio streaming is a method that allows for a particular audio format to be streamed over the internet. This was accomplished yesteryear by our old friend Flash by using a proprietary protocol developed by Macromedia called RTMP (Real Time Messaging Protocol) used to stream audio. Several variants have since been developed by Adobe Systems, the new owners of Flash, offering better security. Today, streaming is also done by icecast, a streaming media server that supports Ogg, Opus, WebM, MP4(H.264, MPEG4) and MP3 streams. And, it is done by SHOUTcast, a free cross-platform proprietary software that streams audio content (MP3, ACC,…). Both icecast and SHOUTcast uses the HTTP protocol to stream audio. Below is a table of codecs supported by stream protocols:

Stream AAC MP3 OGG
icast Yes Yes Yes
SHOUTcast Yes Yes No
RTMP Yes Yes No

Figure 1.3 File type support of streaming protocols

Let us recap on what we will be doing in this project step

  1. Create a UI with controls for our MP3 Player
  2. Include an audio file(s) that can be triggered by our controls to play/pause
  3. Add multiple files to our project folder
  4. Read all audio files from project folder and list them on our mp3 player page
  5. Select an audio file to be played
  6. Play audio files in our playlist

The way we are going to add audio into our web page is by using the HTML5 <audio> tag. Within our audio element we use the controls property item so that basic user controls are displayed for interacting with our audio (play, pause, volume, positional slider). Additionally, we use the source attribute that holds the address of our audio, and we use the type attribute to define the Mime type. In our example we define just one format. Figure 1.1 shows the other options available to the designer. MP3 format is ideal when desiring a small foot print in the ecosystem. MP3 or OGG both are appropriate formats for this. However, there are those audio aficionados who pay close auditory attention to the compression engrained sound of MP3 and OGG files, and still choose to use the higher fidelity sound of WAV files. In this regard, MP3 player is a bit of a misnomer. As pointed out in Figure 1.1 and Figure 1.2, we can use .wav, .acc, .mp3, and .ogg files. And, when using .wav files locally there is little to no latency issues. However, just know from an online web server there is no streaming protocol that supports .wav files (See Figure 1.3).

Now that we’ve gone over the pertinent information in understanding what’s going on, let’s put the puzzle together. For this project I will be using a Windows system, and a Chrome browser. But, you can follow along in your system of choice. Just remember that when typing file paths, Unix-like system will use a back slash (\).

First things first, create a folder on your desktop and name it “HTML MP3 Project”. Inside that folder, create four more folders with the following names:

  1. Css
  2. data
  3. images
  4. js

Now, open your trusty text editor (remember, no word processing programs like MS Word, Open Office, Libre Office or any variants). Once open, ensure you type the following code into the text editor, of course adjusting the audio file names to those you plan to use. You can also adjust the colors to your satisfaction:

Figure 1.4

Figure 1.4 Create main html page – UI

Once you have entered the code into your text editor, name your file index.html or whatever you feel is appropriate for your project and save the file in the “HTML MP3 Project” folder. Let’s look at our <audio> tag (line 26 – 29). This is the basic syntax as pointed out in the <audio> tag selection above. Here we are using only one Mime type for the brevity of this article. The <audio> properties are self-explanatory. But, I will say that by using the controls property we are given the most basic audio control structure (Play/Pause, data slider, and volume). In Lines 12 and 16 we create button images for our next/previous controls. The ontimeupdate attribute on line 26 is linked to a handler for our currentTime and duration events, using the JavaScript function call displayTime(this). Take note of line 4, our link of our css file, and lines 43 and 44, our script tags that include our jQuery library and our JavaScript file (ensure they are in this order). I placed these files at the bottom (ordinarily you may see them in in the html head tag) so that the html DOM (document object model) is completely loaded with all elements before the JavaScript attempts to act upon it.

Now, let’s create our css. Open a text editor, and enter the following code. When finished, name the file mp3.css and save it in the css folder inside of our project folder.

Figure 1.5

Figure 1.5 CSS: mp3.css file part 1

Figure 1.6

Figure 1.6 CSS: mp3.css file part 2

Again, the css is code is fairly intuitive. But, I will say that I’m using lines 26 – 29 to change a playlist item’s color when I hover over with my mouse. Lines 59 – 64, of course, are used to display the output of the currentTime and duration events on the main menu screen.

Open your text editor again, and enter the following JavaScript code. Once finished, name your file “playlist.js” and save it inside the js folder created earlier in your main project folder.

Figure 1.7

Figure 1.7 JS: playlist.js file part 1

Figure 1.8

Figure 1.8 JS: playlist.js file part 2

Line 2 calls our JavaScript initAudio function with a jQuery method, which initializes our audio with the first item in our playlist. The other functions are pretty intuitive. But, I will say that line 66, JavaScript function displayTime, which you probably recognized from Figure 1.4 (line 26 ontimedisplay handler), makes use of the media events duration and currentTime to calculate minutes and seconds. By default these two media events return milliseconds, hence the need for the calculations to get seconds and minutes.

Our next block of code, lines 86 – 97, uses the ended media event to invoke the audio object to play the next track in the playlist. If the track is the last in the playlist, the last track is played until the end (audio stops), and the first track is initialized but not played.

Having created the noted files above, and having followed the code examples, your mp3 application should look similar to Figure 1.0.

As you can see, using HTML5 and JavaScript to implement audio in a web browser is pretty straight forward. The HTML5 spec is easy to understand. So, I encourage you to explore it to access at all the possibilities that HTML5 affords.








2 thoughts on “HTML5: MP3 Player Project Tutorial 2016 Edition

  1. Where does one declare the ‘displayTime’ as a variable, got error message stating that ‘displayTime’ was not declared.

  2. Is there a github repo for this project?

    Thanks for the update. I remember working on the 2012/13 version and it was part of a really helpful PDF and I learned a lot. It was one of the first projects I completed when I was making the career switch to programming.

Leave a Reply

Your email address will not be published. Required fields are marked *