Click here to Skip to main content
14,267,453 members

Create Music Playlist with HTML5 and JavaScript

Rate this:
0.00 (No votes)
Please Sign up or sign in to vote.
0.00 (No votes)
14 Aug 2019CPOL
Learn how to leverage the power of HTML5 audio and video tags

There are many JavaScript libraries for showing videos and playing music contents on a website. However, with advent of HTML5 and its audio and video elements, developers now can easily add video and audio players to their sites without using a third-party JavaScript library. In this tutorial, we review main attributes of audio tag and show you how to create a music playlist by adding some JavaScript codes to it.

Project Background

As a web designer or freelancer, you may run into cases where you need to integrate few audio or video files to a web page. For instance, you are building a website for a nightclub and they ask you to add a music track in the background or a book author wants to add a teaser video on its website. Other cases are where you just need to list few audio or video files on a web page. In all the mentioned scenarios, you can just use simple HTML5 for adding audio or video files to a page. Also, there are two issues with most of JS audio player libraries:

  1. They usually come with many features or options that may not be used in your project; yet, you need to download and use all of library files. It may add additional loads on your server and website.
  2. The JS libraries sometime clash with other JS frameworks or cease functioning when you update your JS framework or CMS plug-in. For example, you may install new version of jQuery not knowing that your audio JS library does not support it. In short, considering shortcoming of third-party JS libraries and easy of using HTML5, it is strongly recommended to use HTML5 audio tags wherever needed.

In this short tutorial, we will show you how to use the HTML5 <audio /> element and expand it to a basic music playlist by means of basic JavaScript.

It is good to know that although in this tutorial, we focus on HTML5 audio tag, all of the topics covered in this tutorial can be applied to HTML5 video tag too. That means, you can create a simple YouTube channel by following this recipe and replacing <audio> with <video> tag.

Project Prerequisites

To follow and finish this tutorial, basic knowledge of HTML5, CSS and JavaScript is required.

Project Files

Click here to download the project source files. You can see its live demo too.

HTML5 Audio Tag Overview

Below is a simple syntax for adding audio in a webpage.

<audio src="./files/audio.ogg">
</audio>

You can check the W3School site to explore basic audio tag elements such as media source, media format, browser support, etc. In this tutorial, we briefly review its main attributes and continue with more advanced usage using JavaScript to do more with HTML5 audio tags.

HTML5 Audio Tag Attributes

The <audio /> Tag comes with attributes that will assist you to manage the behavior of the media on your page. Main attributes are Controls, Autoplay, Loops and Preload.

The Controls attribute comes with the following default audio control components: Play and Pause buttons, Volume control, and the track duration. You can add it to audio tag like below:

<audio controls="controls">
<source src="./files/audio.ogg"/>
</audio>

Autoplay attribute makes the audio run when a page is loaded even without showing the player. You can add this attribute like below:

<audio autoplay="autoplay">
<source src="./files/audio.ogg"/>
</audio>

Loop allows an audio to be played over and over. You can add this attribute like below:

<audio loop="loop"autoplay >
<source src="./files/audio.ogg"/>
</audio>

Preload attribute tells the browser how to treat the media file. This attribute accept the following values:

  1. auto: The browser can download the whole file if it is needed by the user (this is the default value).
  2. metadata: The user may not need the whole media, so the browser can only check for the metadatas (length) of the file, and
  3. none: The browser will not download the file if the user does not need it. This can be used to minimize server load.

The below code tells the browser to not load audio file until a user clicks the Play button.

<audio preload="none">
<source src="./files/audio.ogg"/>
</audio>

Audio Tag with JavaScript

As we discussed in the previous section, using HTML5 tag alone lets the browser download and play the music or audio track. However, we can accomplish more by adding JavaScript code to HTML. Here are few cases where JS comes in handy. For instance, below codes show a simple use of JS for performing play and pause actions on audio.

The HTML code is simple. The JS selects the HTML element by ID and uses audio_info global variable to listen to and manipulate the behavior of audio player. So when we run below code, a user can play and pause audio. To utilize the power of JS in audio tag manipulation, we have to explore HTML audio_info properties and methods in depth.

<audio id="audio1">
<source src="sample.mp3" />
</audio>
<button id="play">Play</button><button id="stop">Stop</button>

The js code for adding Play and Pause functions are:

    var audio_info = document.getElementById('audio1');
    document.getElementById('play').addEventListener('click', function(){
        audio_info.play();
    }, false);
//
    document.getElementById('stop').addEventListener('click', function(){
        audio_info.pause();
    }, false);

HTML5 Media Properties

The audio_info global variable can take the following properties:

  • autoplay: Act like the value of the attributes (seen in the previous section).
  • currentTime: Contains the current playback time, in seconds. Setting this property will set the playback time at the value defined.
  • duration: (Read-Only) The length, in seconds.
  • paused: (Read-Only) Indicates if the playback is paused or not.
  • volume: It gets or sets the volume of the media element : 0.0 is silent, and 1.0 is the loudest.

HTML5 Media Methods

The element also has some methods, we’ve seen play() and pause() in our previous section, here are the others:

  • canPlayType (mimetype): Determine if the browser can play the mimetype passed in argument. This function can return: nothing (empty string) if the browser cannot play the type, probably if the browser seems to be able to play the type, maybe if it’s impossible to tell if the type is playable or not.
  • fastSeek (time): This will seek directly to the given time.
  • load(): This method will begin loading the media from the server

When actions are made with the <audio /> tag, some events are fired, let's go over some events before using all together with our music playlist project.

HTML5 Media Events

Here is a list of events that we can use with audio element:

  • progress: The user agent is fetching media data.
  • error: An error occurs while fetching the media data.
  • play: Playback has begun. Fired after the play() method has returned, or when the autoplay attribute has caused playback to begin.
  • pause: Playback has been paused. Fired after the pause() method has returned.
  • loadeddata: The user agent can render the media data at the current playback position for the first time.
  • waiting: Playback has stopped because the next frame is not available, but the user agent expects that frame to become available shortly.
  • playing: Playback has started.
  • canplay: The user agent can resume playback of the media data, but estimates that if playback were to be started now, the media resource could not be rendered at the current playback rate up to its end without having to stop for further buffering of content.
  • seeking: The seeking IDL attribute changed to true and the seek operation is taking long enough that the user agent has time to fire the event.
  • seeked: The seeking IDL attribute changed to false.
  • timeupdate: The current playback position changed as part of normal playback or in an especially interesting way, for instance discontinuously. Note: This event will be fired every second.
  • ended: Playback has stopped because the end of the media resource was reached.
  • volumechange: Either the volume attribute or the muted attribute has changed. Fired after the relevant attribute’s setter has returned.

More events can be found at: http://www.w3.org/wiki/HTML/Elements/audio#Media_Events

Music Player

Now that we learned how to use JS in conjunction with HTML5 audio tag, it is time to put things together and build our music player. As a reminder, the list of events that we reviewed in the previous section will come in handy while creating our music player. We divide our project into two parts. In the first part, we run HTML and JS to get information about audio elements by using few events. In the second part, we fully expand our script to build our music playlist.

Get Audio Element Info

In this part, we will show information in the browser console by using the following HTML and JS codes.

//HTML part
<audio id="audio2" controls>
    <source src=" sample.mp3" />
</audio>
//JS part
    var audio_info = document.getElementById('audio2');
    audio_info.addEventListener('playing', function(e){
        console.log('Audio playback has started ...');
        console.log('Playback started at : '+ e.target.currentTime +" seconds");
    }, false);
    audio_info.addEventListener('pause', function(e){
        console.log('Audio playback has been paused ...');
        console.log('Playback paused at : '+ e.target.currentTime +" seconds");
    }, false);

    audio_info.addEventListener('ended', function(e){
        console.log('Playback has ended');
    }, false);
    audio_info.addEventListener('volumechange', function(e){
        console.log("Volume has changed ...");
        console.log("Volume is now "+ e.target.volume);
    }, false);

In the previous JS codes, we accomplish the following: First, we get the audio element by its ID and store it in a variable: audio_info, then we add listeners on the audio element for the following events:

  • playing, callback will log the string: Audio playback has started and an info about the currentTime of the element, when the user click on the play button. Try to start, pause, then start again to see the currentTime info updated.
  • playing, this is fired when the media has been paused. When the user pauses the playback, callback will be called.
  • ended, this is fired when the media has ended.
  • volumechange, this is fired when the volume (of the element, not your computer) has changed, callback will log volume value.

For all the events we used the event target to get information about the audio element, we did not use the audio_info variable. Here, we tried an alternative solution to audio_info global variable (discussed in the previous section). So you can use either of them in your music playlist project. That means, you can make a choice between using global scope variable versus event target to get information on an audio element.

Playlist Part

Now we move on to the second part and use the <audio /> element in a real music playlist. In this part, we create a small tool that will play multiple files; it means that at the end of a file, the player will start the next audio file. We will also allow the user to stop the music, and to change the volume.

Here is the HTML code:

<div id="music_list">
    <audio controls autoplay></audio>
</div>

And the JavaScript code:

function () {
    // Playlist array
    var files = [
        "sample1.mp3",
        "sample2.mp3",
        "sample3.mp3"
    ];

    // Current index of the files array
    var i = 0;

    // Get the audio element
    var music_player = document.querySelector("#music_list audio");

    // function for moving to next audio file
    function next() {
        // Check for last audio file in the playlist
        if (i === files.length - 1) {
            i = 0;
        } else {
            i++;
        }

        // Change the audio element source
        music_player.src = files[i];
    }

    // Check if the player is selected
    if (music_player === null) {
        throw "Playlist Player does not exists ...";
    } else {
        // Start the player
        music_player.src = files[i];

        // Listen for the music ended event, to play the next audio file
        music_player.addEventListener('ended', next, false)
    }

})();

Obviously, you can improve this JS coding by connecting the JS to a database via Ajax or Node.JS to load audio files or adding fancier CSS styling to it. Likewise, you can use jQuery selectors for selecting and manipulating HTML elements.

Conclusion

The HTML5 <audio /> offers the ability to easily embed sound into your webpage. As we discussed and reviewed its properties, methods and events, you noticed that we can accomplish more by using simple JS code along with our HTML5 audio tags. Also, if you like to use HTML5 <video> tag instead of audio, you can still follow and use topics discussed in this tutorial.

It is good to know that until you use a server-side coding language or encrypt your JS codes; all music track source files are visible to your site visitors (that means, they can download them for free). So if you like to create a simple e-commerce site for selling your albums or charge users for your music songs, you need to do additional server-side coding.

History

  • 14th August, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


Comments and Discussions

 
QuestionMajor confusion... Pin
Dewey15-Aug-19 6:24
memberDewey15-Aug-19 6:24 
AnswerRe: Major confusion... Pin
Pete Lomax Member 106645059hrs 29mins ago
professionalPete Lomax Member 106645059hrs 29mins ago 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 14 Aug 2019

Stats

1.3K views
4 bookmarked