Codementor Events

HTML and JavaScript audio player

Published Aug 02, 2022Last updated Jul 30, 2023
HTML and JavaScript audio player

In this article you will read about how to make an audio player for your website or Open edX LMS with royalty free music in JavaScript and HTML, if you are wondering how to do it, you are here.
Also check out our HTML tutorial if you don't know it well.

Creating an audio player:

First, let's analyze the logic of the player and what we implement here, and implement the switching of tracks, and the playlist itself, as for the pause, then in HTML already by standard it is.

HTML:

Let's start with HTML, there is nothing complicated here, just write the tag < audio> inside the document and add an attribute controls.

XHTML

<audio id="audio" src="./audio/treck1.mp3" controls></audio>

Here's the result.
image1.jpeg
As you can see the standard HTML player looks nice, but there is one problem, its capabilities are limited, you can only stop the track and change the volume and all, which in my opinion is not enough, so we will remove the attribute controls, after which we will have an empty screen.
Since we now have a blank screen, we will add buttons to control, also a tag for the audio tracks.
XHTML

<div id="controls">
    <div class="audio-track"><div class="time"></div></div>
    <button class="play">Play</button>
    <button class="pause">Pause</button>
    <button class="prev">&#60;prev</button>
    <button class="next">next&#62;</button>
</div>

Let's break it down, < div> with the class audio-track, this is the audio track, inside it there is a < div> with the class time, this is the remainder of how long there is left to finish.
Also go next are four tags < button> , this button, the first to play music, the second to pause, the third switches to the previous track, the fourth button to the next.

CSS:

Now let's move on to CSS, with its help we will change only the track, we will leave the buttons by default, as they are made in the browser.
CSS

.audio-track {
    width: 150px;
    height: 3px;
    background-color: #dddddddddd;
    margin: 20px 0
}
 
.time {
    width: 0;
    height: 3px;
    background-color: #474747
}

This is what came out.
image2.jpeg
We have a small track, gray, and when playing it will be almost black due to the increase in < div> with the class time.

JavaScript:

It's time for the most important thing, to create the basic logic in pure JavaScript, first we'll take all the elements from the HTML.
JavaScript

let audio = document.getElementById("audio"); // Take the audio element
let time = document.querySelector(".time"); // Take the audio track
let btnPlay = document.querySelector(".play"); // Take the play button
let btnPause = document.querySelector(".pause"); // Take the pause button
let btnPrev = document.querySelector(". prev"); // Take the switch button of the previous track
let btnNext = document.querySelector(".next"); // Take the button to switch the next track

Here we just take the elements we will work with, we take the < audio> element through the id and the rest through the selector.
Next, let's make an array with track names and a variable that will store the index of the track in the array.
JavaScript

// Array with song titles
let playlist = [
    'treck1.mp3',
    'treck2.mp3',
    'treck3.mp3',
    'treck4.mp3',
];
 
let treck; // Variable with track index
 
// Event before page loading
window. onload = function() {
    treck = 0; // Assign zero to the variable
}

The most interesting thing in this code is window. onload, it needs to perform some actions when the page loads, in our case, it assigns a value of zero to the treck variable.
A lot of people have questions about why we should assign a value to a variable at page load time and not at declaration time because otherwise its value would always be zero, and we need to use it to switch songs.
Now let's move on to the function for switching songs.
JavaScript

function switchTreck (numTreck) {
    // Change the src attribute value
    audio.src = './audio/' + playlist[numTreck];
    // Assign a song time of zero
    audio. currentTime = 0;
    // Play the song
    audio.play();
}

In the beginning we pass the index of the song we need in the function, then we change the path to the track, using audio. src, we assign the path to the song we need by taking the song name from the playlist.
Then we assign audio. currentTime value of zero, it is responsible for the minute the song is playing, that is, we put the song on zero second.
The last one is to run the song through audio. play().
Now let's move on to processing the events of these buttons, to work with the player and music.
JavaScript

btnPlay.addEventListener("click", function() {
    audio.play(); // Start the song
    // Start interval 
    audioPlay = setInterval(function() {
        // Get the value of what second the song is at
        let audioTime = Math.round(audio.currentTime);
        // We get songs all the time
        let audioLength = Math.round(audio.duration)
        // Assign a width to an element at time
        time.style.width = (audioTime * 100) / audioLength + '%';
        // Compare what second the track is now and how long in total
        // And check that the treck variable is less than four
        if (audioTime == audioLength && treck < 3) {
            treck++; // then Increase the variable 
            switchTreck(treck); // change track
        // Otherwise we check the same, but the treck variable is greater than or equal to four
        } else if (audioTime == audioLength && treck >= 3) {
            treck = 0; // then we assign treck to zero
            switchTreck(treck); Change track
        }
    }, 10)
});

This is probably the most difficult part of the program, when we press the "Play" button.
The first thing we start playing the song, then we start the interval, we need it to track when to switch to the next track.
Inside the interval, we assign the variable audioTime to the second at which the track is now, and the variable audioLength, we assign the total number of seconds the song lasts, then calculate by formula how much of the song has already played and assign this value to the width of the element time, thereby we have created a progress line.
A condition where we check that the variable audioTime and audioLength, it is necessary to make sure that the song ended, also check the variable treck, that it was less than three, it is necessary that its value is not greater than the array index and the songs have not stopped.
If the condition is true, then increase the treck variable and change the song using the switchTreck function.
Otherwise, again we check that the song is over, but now we look for the variable treck to be greater than or equal to three, if it is true we assign it zero and also change the track.
The next step is the processing of the pause button.
JavaScript
1
2
3
4 btnPause.addEventListener("click", function() {
audio.pause(); // Stops the song
clearInterval(audioPlay) // stops the interval
});
There is nothing to tell, everything is clear from the comments to the code.
The last thing you need to figure out is the song switching buttons, that's how you switch to the previous one.
JavaScript

btnPrev.addEventListener("click", function() {
    // Check that the treck variable is greater than zero
    if (treck > 0) {
        treck--; // If true, reduce the variable by one
        switchTreck(treck); // Change the song.
    } else { // Otherwise
        treck = 3; // Assign three
        switchTreck(treck); // Change the song
    }
});

I think it's clear from the comments, I won't explain what's what. Here's how to switch to the next song.
JavaScript

btnNext.addEventListener("click", function() {
    // Check that the treck variable is greater than three
    if (treck < 3) { // If so
        treck++; // increase it by one
        switchTreck(treck); // Change the song 
    } else { // Otherwise
        treck = 0; // Assign a zero to it
        switchTreck(treck); // Change the song
    }
});

That's where it ends, everything works fine and here's the result.
image3.jpeg

Conclusion:

In this article you saw how to make an audio player in JavaScript and HTML, I think you liked it.
It should also be said that there is still a lot to be improved and do, for example, the output of all the tracks or change the volume, etc.
But then the article would be very large, in my opinion it is not small enough, so I did not do it.
But if you want to refine the audio player in JavaScript, download its files and go to this link, there is everything you need to know to work with audio in JS.

Discover and read more posts from emiliabartner
get started
post comments2Replies
Mikayla Figueroa
5 months ago

<a href=“https://www.daraz.pk/shop/rising-star/”>Fan for gree</a>

overton031
a year ago

Creating seamless audio on web pages is important, and combining HTML and JavaScript for an audio player increases user engagement. With tools like https://liveradioau.com/, web developers can easily integrate dynamic audio content, enriching websites with live radio streams. This allows various platforms to provide an immersive listening experience and helps connect and entertain online audiences.