Html5 Audio format

audio current time

by Master P

HTML

<button id=pButton>Play</button>
  <p id="start-time" class="time"></p>
 <p id="duration" class="time">00:00</p>

CSS

body {
  background-color:black;
}

#pButton{
 
  background-color: #424242;
  border: 2px solid #bdbdbd;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;
  font-size: 25px;
  color:  #bdbdbd;
  float:left;
  outline:none;
  position: relative;
  cursor: pointer;
  padding:20px;
}

#duration,
#start-time{ 
     padding: 20px;
     float: left;
}

.time {
    font-size: 20px;
    color: black;
    position: relative;
    top: 0px;
 
  min-width: 60px;
}

JavaScript

const audio = document.createElement("AUDIO");
audio.setAttribute("id", "audio");
audio.src = "http://www.hscripts.com/tutorials/html/music.wav";
audio.controls = true;
audio.onloadedmetadata = function() {
  document.getElementById("duration").style.color = "#bdbdbd";
  document.getElementById("start-time").style.color = "white";
  
  
  
  
  // buttons
  document.getElementById("pButton").addEventListener("click", function (){
  
   // Toggle audio play
  audio[audio.paused ? "play" : "pause"]();
  
  });

  // Convert duration into HH:MM:SS
  duration(audio.duration);
  
};





// function converts audio.duration to SS:mm format
function duration(time) {
  var minutes = parseInt(time / 60, 10);
  var seconds = parseInt(time % 60);
  var millisecondsCal = time % 60;
  var milliseconds = ("0" + millisecondsCal).substr(4, 2);
  
  console.log(seconds);
  
  // create empty vars to store values
  var minResult = '';
  var secResult = '';
  var millResult = '';
  
   // only display 00:00.00 formats if the mp3 requires it
  if (minutes === 0 ) {
  minResult = '\u00a0';
  } else {
   minResult = minutes + ':';
  }
   if (seconds === 0 ) {
  secResult = '\u00a0';
  } else {
   secResult = seconds + '.';
  }
   if (millisecondsCal === 0 ) {
  millResult = '\u00a0';
  } else {
   millResult = milliseconds;
  }

  // append value to dom
  document.getElementById("duration").innerHTML = minResult + secResult + millResult;
}

// convert audio.currentTime to SS:mm format
function format() {
  var secsCal = Math.floor(audio.currentTime % 60);
  var minsCal = Math.floor(audio.currentTime / 60);
  var millsCal = audio.currentTime % 60;
  

  var secs = ("0" + secsCal).substr(-2);
  var mins = ("0" + minsCal).substr(-2);
  var mills = ("0" + millsCal).substr(4, 2);
  
  // create empty vars to store values
  var minResult = '';
  var secResult = '';
  var millResult = '';
  
  // only display 00:00.00 formats if the mp3 requires it
  if (minsCal === 0 ) {
  minResult =...