Audio Player using HTML5 and JavaScript

Please select a song from the list


 

I started this work just to learn about audio tag in html5. My objective was to choose songs from a list and play it using audio tag. This audio player has following controls.

  1. Play/Pause
  2. Rewind
  3. Fast-forward
  4. Previous
  5. Next
  6. Stop
  7. Restart
  8. Volume up
  9. Volume down.

Let us implement it in three steps.

  1. List the songs using a list box
  2. Display the audio controls
  3. Button controls.

Step 1: List the songs using list box

To check the browser compatibility I tried different types of audio files such as .mp3,.wav and .ogg.
List the songs using ‘select’ & ‘option’ tags with the id as ’mylist’ .The option has two attributes id and value. The id represents the unique identification value for that particular option and the ‘value’ represents the items or audio files in this case. ‘id’ helps us to identify different files.

<p>Please select a song from the list
<select name=mylist id=mylist onChange=”playAudio();”>
<option id=”1″ value=”mp3-sample.mp3″>MP3
<option id=”5″ value=”wav-sample.wav”>WAV
<option id=”6″ value=”oog-sample.ogg”>OOG
</select>
</p>

You might have noticed onChange=”playAudio()” in the selection tag. playAudio() is a JavaScript function to play the music which will be discussed later. The player plays the music as soon as you select the song from the list. This is the reason for calling the function on ‘onChange’ event.

Step 2: Display the audio controls

To display the audio controls ‘audio’ is used.

<audio id=”myaudio” controls=”controls” preload=”auto”>
HTML5 audio not supported
</audio>

Now we have an audio tag with id “myaudio” and three other attributes. The possible attributes for an audio tag is given below.

Attribute Value Description
autoplay autoplay Specifies that the audio will start playing as soon as it is ready
controls controls Specifies that audio controls should be displayed (such as a play/pause button etc).
loop loop Specifies that the audio will start over again, every time it is finished
preload auto,metadata,none Specifies if and how the author thinks the audio should be loaded when the page loads
src URL Specifies the URL of the audio file

A characteristic of the HTML language is that if a tag is not recognised, it is ignored. In a browser that does not support HTML5, when you use the HTML5 audio element, if it is not recognized, the portion between the tags is used. In this example, the message HTML5 Audio is not supported is displayed.

Step 3: Button controls

1.Play/ Pause

As the name suggests this button is to play or pause the audio file.

<button id=”play” onClick=”playAudio(); “>Play/Pause</button>

The play and pause methods are used to provide playback control. The button object is retrieved so that the button label can be toggled between Play and Pause, depending on the state of the audio object’s paused property. The state is checked every time the “playAudio” function is called. If the audio file is playing, the paused property returns false, and the pause method is called to pause the playback. The button label is also set to Play.

If the file is paused, the paused property returns true, and the play method is called, the button label is updated to Pause. When a file is first loaded, the paused property returns true (playback is paused) even though the pause method has not explicitly been called.

In the JavaScript portion, using document.getElementById, the audio object is returned in oAudio, the button object is returned in btn and list object is returned in audioURL. To play more than one file, you can set the audio object’s src property to a URL of an audio file from within JavaScript.

The global variable “currentFile” is defined so that it keeps track of the URL for the file that is currently playing. When the user clicks the Play button, the “currentFile” variable is compared to the value in the text field that is specified by “audioURL.value”. If these values are different, the src property is set to the new file URL, the “currentFile” variable is updated, and the load method is called.

var currentFile = “”; //Global variable to track current file
function playAudio() {
// Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById(‘myaudio’);
var btn = document.getElementById(‘play’);
var audioURL = document.getElementById(‘mylist’); //Skip loading if current file hasn’t changed.
if (audioURL.value !== currentFile) {
oAudio.src = audioURL.value;
currentFile = audioURL.value;
}// Tests the paused attribute and set state.
if (oAudio.paused) {
oAudio.play();
btn.textContent = “Pause”;
}
else {
oAudio.pause();
btn.textContent = “Play”;
}
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error(“Error:” + e));
}
}
}

In the JavaScript section of the code, there are areas where errors are likely. The first is when you check for HTML5 audio support. Each function tests by using if (window.HTMLAudioElement) to see if the audio element exists. If the audio element does not exist no code is executed.

If HTML5 audio is supported, there are other errors that might happen. Try/catch statements are used in conjunction with methods that can throw exceptions. One cause of exceptions is if the user tries to play a file that does not exist, rewind when no file is loaded, or a connection to a file cannot be made.

With the try/catch statements, these conditions fail silently, but you can see the errors if you open either the Console or Script tab in Internet Explorer 9 F12 tools. For example, the Fast Forward, Rewind, and Restart functions throw “InvalidStateError” DOMExceptions if there is no audio file playing or loaded.

2.Rewind

While an audio file is playing, the currentTime property tracks where the playback is in the audio clip. By changing the value of currentTime, you can skip forward or backward, or restart the playback. The rewindAudio decrements the value of currentTime by 30secs. You can change this value to create smaller or larger jumps.

function rewindAudio() {
// Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById(‘myaudio’);
oAudio.currentTime -= 30.0;
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error(“Error:” + e));
}
}
}

3.Fast-forward

This also can be done using the currentTime property which tracks where the playback is in the audio clip. To fast forward the file current time is incremented by 30secs. You can change the value if you want to create smaller or larger jumps.

// Fast forwards the audio file by 30 seconds. function forwardAudio() {// Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById(‘myaudio’);
oAudio.currentTime += 30.0;
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error(“Error:” + e));
}
}
}

4.Restart

In the restartAudio function, the value of currentTime is set to zero, which is the beginning of the file and thus the file again starts from the beginning.

// Restart the audio file to the beginning.

function restartAudio() {
var btn = document.getElementById(‘play’);

// Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById(‘myaudio’);

// oAudio.currentTime = 0;
var lb = document.getElementById(‘mylist’);
oAudio.src=lb.value;
oAudio.play();
btn.textContent = “Pause”;
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error(“Error:” + e));
}
}
}

5.Stop

To stop the execution of the current file, we can use the method Stop() along with the audio object. When the file gets stopped the play/pause button also should be changed to ‘play’ mode.

function AudioStop()
{
var oAudio = document.getElementById(‘myaudio’);
var btn = document.getElementById(‘play’);
btn.textContent = “Play”;
var lb = document.getElementById(‘mylist’);
oAudio.src=lb.value;
oAudio.Stop();
}

6.Previous

This button helps us to go to the previous song in the given list. To play the previous song first we should know the ‘id’ of the current file, which we can get from the listbox object(lb). The instruction lb.value will give you the current file. Then we need to compare the files in the list with current running file. By default the list items are in a built-in array named options. We can access the files in the list using options[i].value. Length of this array can be found using listboxobject.options.length. ‘i’ can be any value from zero to length-1(Array index starts from zero).The variable curfile will have the id of the current file. Compare the ids in the array with lb.options[i].value and change the src attribute of the audio object (oAudio) to the previous file id. If we are in the first file of the list, display message saying ‘This is the first file’. Else it will play the previous song.

//function to select previous song
function Previous()
{
var oAudio = document.getElementById(‘myaudio’);
var btn = document.getElementById(‘play’);
var lb = document.getElementById(‘mylist’);
var curfile= lb.value; for(i=0; i<=lb.length; i++) {if(curfile== lb.options[i].value){
if(i!=0){ //To check the beginning of the LIST OF FILES
j=i-1; // points to the previous file id
oAudio.src=lb.options[j].value;
oAudio.play();
lb.options[j].selected=true;
btn.textContent = “Pause”;
}
else{ // If curfile is the first file in the list of files
btn.textContent = “Play”;
window.alert(“This is the first song”);
}}
}
}

7.Next

This button is used, to go to the next song in the given list. The logic used for the ‘Previous’ button is used here with a difference that the control goes to the next file than to the previous file. If the current file is the last file, it shows the message “This is the last song”.

// Function to select next song
function Next()
{
var oAudio = document.getElementById(‘myaudio’);
var btn = document.getElementById(‘play’);
var lb = document.getElementById(‘mylist’);
var curfile= lb.value;
var count=lb.options.length // To count the number of files/* please note that counting starts from 1 whereas array options[] index starts from zero*/
if(curfile!=lb.options[count-1].value){
for(i=0; i<lb.options.length; i++){
if(curfile==lb.options[i].value){
j=i+1;
oAudio.src=lb.options[j].value;
oAudio.play();
lb.options[j].selected=true;
btn.textContent = “Pause”;
}
}
}
else{
window.alert(“This is the last song”);
btn.textContent=”Play”;}
}

8.Volume controls: Up/Down

To increase/decrease the volume, we can use the volume attribute of the audio object in the following way. Here, volume is increased/decreased by 0.1.

// increases the volume
<button onClick=”document.getElementById(‘myaudio’).volume+=0.1″>Volume Up</button>

// decreases the volume
<button onClick=”document.getElementById(‘myaudio’).volume-=0.1″>Volume Down</button>

Thank you so much for taking time and going through this tutorial, Hope it has been helpful to you.



    We create Multilingual websites, E-Commerce websites, Corporate websites, Appointment booking websites, web portals

    Al Aman | Dolomia

    ECOMMERCE | BILINGUAL (ENGLISH/ARABIC) | ALAMANKW.COM

    We specialise in

    • Creating business brands
    • Corporate Websites
    • Print/Marketing material
    • Optimising websites for search engines (SEO)
    • Promoting business on search engine through Google ads
    •  HTML5 animations

    We are creative and patient listeners, open to hear your thoughts, your ideas, your perspectives for your business branding and showcasing it in digital space.

    To understand the quality of our work, please view our portfolio or write to us at reachout[at]imajineweb[dot]com.