HTML5 Audio Tag with Progress

In this example below you will see how to do a HTML5 Audio Tag with Progress with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by 1Marc, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 1Marc ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>HTML5 Audio Tag with Progress</title>
  
  
  
  
  
</head>

<body>

  <audio id="my-audio" preload="auto">
  <source src="http://jPlayer.org/audio/mp3/Miaow-01-Tempered-song.mp3" type="audio/mpeg">
  <source src="http://jPlayer.org/audio/ogg/Miaow-01-Tempered-song.ogg" type="audio/ogg">
</audio>

<div id="played-bar">00</div>
<div id="buffer-bar">00</div>
<div id="control-bar">
   <a href='0'>00</a> <a href='10'>10</a> <a href='20'>20</a> 
   <a href='30'>30</a> <a href='40'>40</a> <a href='50'>50</a> 
   <a href='60'>60</a> <a href='70'>70</a> <a href='80'>80</a> 
   <a href='90'>90</a>
</div>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/1Marc/html5-audio-tag-with-progress-jyeEa */
window.onload = function(){
  var myAudio = document.getElementById('my-audio');
  var controlBar = document.getElementById('control-bar');
  
  // we add our listeners
  myAudio.addEventListener('timeupdate', updatePlayed, false);
  myAudio.addEventListener('progress', updateBuffered, false);
  
  function updatePlayed() {
     var played = parseInt(((myAudio.currentTime / myAudio.duration) * 100), 10);
     // gives us a percentage
     addBars(played,'played-bar');
  }
  
  function updateBuffered() {
     var loaded = parseInt(((myAudio.buffered.end(0) / myAudio.duration) * 100), 10);
     // gives us a percentage 
     addBars(loaded,'buffer-bar'); 
  } 
  
  function addBars(amount,element) {
     var bars = "00";
     // since our bars are in increments of 10
     for (i=10; i < 100; i = i + 10) {
        if (i <= amount) {
           bars = bars + " " + i;
        }
     }
  
     var bar = document.getElementById(element);
     bar.innerHTML = bars;
  }
    
  controlBar.onclick = setTime;
  
  function setTime(e) {
    e.preventDefault();
    
    var playPosition = e.target.getAttribute('href'); // from 0 to 90
    myAudio.currentTime = (myAudio.duration * playPosition)/100;
    myAudio.play();
    return false;
  }   

}

Comments