Make A Dynamic Audio Progress Bar
April 17, 2025
You will learn how to make a simple dynamic progress bar that loads with the current time of an HTML audio element.
What you will need:
- Vue CDN - my frontend framework of choice
- Tailwind CDN (optional) - for fast CSS styling
The Code
html
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Application</title>
<script src='https://cdn.tailwindcss.com'></script>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body id="app">
<audio id="audioPlayer" class="hidden" controls ref="audioPlayer">
<source src="Chorus_.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<section class="mt-8 rounded-2xl p-4 bg-zinc-200 container w-1/2 mx-auto">
<div class="mt-2 w-full hp_slide bg-zinc-800 h-[5px]">
<div class="w-0 hp_range bg-red-500 h-[5px]"></div>
</div>
<button class="mt-4 bg-black px-4 py-2 rounded-lg text-white" @click="playMusic()">Play</button>
</section>
<script>
const { createApp, ref, onMounted } = Vue
createApp({
setup() {
onMounted(() => {
progressBar()
})
function progressBar() {
let player = document.querySelector("#audioPlayer");
player.addEventListener("timeupdate", function () {
var currentTime = player.currentTime;
var duration = player.duration;
const all_ranges = document.querySelectorAll('.hp_range');
all_ranges.forEach((a) => {
a.style.width = (currentTime + 0.25) / duration * 100 + '%';
})
});
}
function playMusic() {
this.$refs.audioPlayer.play();
}
return {
playMusic
}
}
}).mount("#app")
</script>
</body>
</html>
How it Works
- It selects the
audioPlayer
element usingdocument.querySelector
. - It adds an event listener to the
timeupdate
event of theaudioPlayer
, which is triggered when the playback of the audio content is updated. - Within this event handler, it calculates the current time and duration of the audio content.
- It then updates the width of each
.hp_range
element using CSS styles, based on the progress bar's calculated value. This creates a visual representation of the audio player's progress.