Search code examples
javascriptjquerytimemedia-playeraudio-player

I can't convert .duration or .currentTime to MM:SS in java script


since I don't know JavaScript I downloaded an audio player and changed the html and CSS but the audio player shows audio duration in seconds and; I tried to look for results in google but that did not work as well, I even tried to copy code from other audio players but it did not work. I would be happy if anyone help me.

thanks...

$(document).ready(function() {

  var timeDrag = false; /* Drag status */
  var isPlaying = false;
  var theSound = $("#firstTrack");
  var allIcons = $("i");
  var isLoaded = false;


  theSound.on("timeupdate", function() {
    var currentPos = theSound[0].currentTime; //Get currenttime
    var maxduration = theSound[0].duration; //Get video duration
    var percentage = 100 * currentPos / maxduration; //in %
    $('.timeBar').css('width', percentage + '%');
    $("#getTime").html(Math.floor(theSound[0].duration));
    $('#goTime').html(Math.floor(theSound[0].currentTime));
  });

  $("#playIt").click(function(event) {

    // run once.
    if (!isLoaded) {
      theSound.trigger('load');
      setTimeout(startBuffer, 500);
      isLoaded = true;


    }

    // toggle play/pause
    if (!isPlaying) {

      theSound.trigger('play');

      $("#playIt").find(allIcons).removeClass("fa-play");
      $("#playIt").find(allIcons).addClass("fa-pause");

      isPlaying = true;

    } else {

      theSound.trigger('pause');

      $("#playIt").find(allIcons).removeClass("fa-pause");
      $("#playIt").find(allIcons).addClass("fa-play");

      isPlaying = false;

    }
  });

  $("#stepFive").click(function() {
    var currentPos = theSound[0].currentTime + 5;
    theSound[0].currentTime = currentPos;
  });


  $("#stepFiveback").click(function() {
    var currentPos = theSound[0].currentTime - 5;
    theSound[0].currentTime = currentPos;
  });

  $('.progressBar').mousedown(function(e) {
    timeDrag = true;
    updatebar(e.pageX);
  });

  $(document).mouseup(function(e) {
    if (timeDrag) {
      timeDrag = false;
      updatebar(e.pageX);
    }
  });
  $(document).mousemove(function(e) {
    if (timeDrag) {
      updatebar(e.pageX);
    }
  });

  //update Progress Bar control
  var updatebar = function(x) {
    var progress = $('.progressBar');
    var maxduration = theSound[0].duration; //Video duraiton
    var position = x - progress.offset().left; //Click pos
    var percentage = 100 * position / progress.width();

    //Check within range
    if (percentage > 100) {
      percentage = 100;
    }
    if (percentage < 0) {
      percentage = 0;
    }

    //Update progress bar and video currenttime
    $('.timeBar').css('width', percentage + '%');
    theSound[0].currentTime = maxduration * percentage / 100;
  };

  //loop to get HTML5 video buffered data
  var startBuffer = function() {

    var maxduration = $("#firstTrack")[0].duration;
    var currentBuffer = $("#firstTrack")[0].buffered.end(0);
    var percentage = 100 * currentBuffer / maxduration;
    $('.bufferBar').css('width', percentage + '%');

    //re-loop if not entierely buffered
    if (currentBuffer < maxduration) {
      setTimeout(startBuffer, 500);
    }

  };

});
@charset "utf-8";

/*head*/

html,
html * {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #1e1f1f;
  max-height: 100vh;
  /* change here */
}


/* -- */

.noPad {
  padding: 0;
}

.playBar {
  transition: all 0.5s ease;
  height: 10px;
  background-color: rgba(186, 44, 44, 0.59);
  /*border: 1.5px;*/
  /*border-color: black;*/
  /*border-style: inset;*/
  opacity: 0.85;
  width: 0;
}

#audioCtrl>div {
  margin: 0;
  padding: 0;
}

.progressBar {
  position: relative;
  width: 100%;
  height: .4em;
  backgroud-color: #474848;
  color: #474848;
  scroll-behavior: smooth;
  border: solid;
  border-color: #474848;
  border-width: 1px;
  border-radius: 5px;
}

.timeBar {
  transition: all 0.5s ease;
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 100%;
  background-color: #8c8d8e;
  border-radius: 5px;
}

.bufferBar {
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 100%;
  background-color: #474949;
  opacity: 0.5;
  border-radius: 5px;
}


/* -- */

.row {
  /* background-color: #535252; */
  border-radius: 10px;
}

.img-container img {
  margin-top: 10em;
  border-radius: 15px;
  height: 22em;
}

.navigation {
  display: flex;
  align-items: center;
  justify-content: center;
}

.info1 {}

.title {
  font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, "sans-serif";
  font-size: 1.7em;
  margin: 0;
  padding-bottom: .4em;
  margin-left: .2em;
  color: #f1f1f1;
}

.time-btn {
  float: right;
  margin-top: .3em;
  background-color: #1E1F1F;
  color: aliceblue;
  border: 0;
  font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
  font-size: 1em;
  margin-right: .3em;
}

.time-btn2 {
  margin-top: .3em;
  background-color: #1E1F1F;
  color: aliceblue;
  border: 0;
  font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
  font-size: 1em;
  margin-left: .2em;
}

.btn {
  background-color: #1e1f1f;
  color: #D7D7D7;
  border: 0;
  font-size: 2.2em;
  padding: .3em .7em;
}

.btn-big {
  color: #FFFFFF;
  font-size: 2.4em;
}

.btn:focus {
  border: 0;
}

.scrollformore {
  color: #FFFFFF;
  font-family: "Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, "sans-serif";
  font-size: 1em;
  margin-top: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
  <title>audio_player_2</title>
  <link rel="stylesheet" href="assets/css/styles.css">
  <link rel="stylesheet" href="assets/css/aistyles.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css" />
</head>

<body>
  <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
  <script src="simple_player.js"></script>
  <div class="container-fluid"><audio id="firstTrack" width="100%" preload="none">
    
                  <source src="https://www.bensound.com/bensound-music/bensound-ukulele.mp3" type="audio/mpeg" />
          
                </audio>

    <div class="img-container"><img src="https://www.bensound.com/bensound-img/ukulele.jpg" alt="cover"></div>

    <h2 class="title info1">Ukulele</h2>

    <div class="row" id="audioCtrl">
      <div class="col-xs-3 progressBar">
        <div class="bufferBar"></div>
        <div class="timeBar"></div>
      </div>
      <div class="col-xs-3"><button class="time-btn info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="getTime"><div class="durationTime">00</div></span></i></button></div>

      <div class="col-xs-3"><button class="time-btn2 info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="goTime"><div class="currentTime">00</div></span></i></button></div>

      <div class="navigation">
        <div class="col-xs-3"><button class="btn btn-default blackb" id="stepFiveback" type="button"> <i class="fa fa-backward"> <span class="hidden-xs"></span></i></button></div>
        <div class="col-xs-3"><button class="btn btn-default blackb btn-big" id="playIt" type="button"> <i class="fa fa-play"> </i></button></div>
        <div class="col-xs-3"><button class="btn btn-default blackb" id="stepFive" type="button"> <i class="fa fa-forward"> <span class="hidden-xs"></span></i></button></div>
      </div>
    </div>
  </div>
  </div>
  <script src="assets/js/jquery.min.js"></script>
  <script src="assets/bootstrap/js/bootstrap.min.js"></script>
  <script src="assets/js/simple_player.js"></script>
</body>

</html>

strong text


Solution

  • You will want to add a function to help convert all the Seconds to Minutes and Seconds.

    Consider the following Example.

    function convertSeconds(sec) {
      var m = Math.floor(sec / 60);
      var s  = sec % 60;
      return (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
    }
    

    This get the calculated Minutes and Seconds from a total number of Seconds using Division and Modulus. It may look like this in use:

    $(document).ready(function() {
    
      var timeDrag = false; /* Drag status */
      var isPlaying = false;
      var theSound = $("#firstTrack");
      var allIcons = $("i");
      var isLoaded = false;
    
      function convertSeconds(sec) {
        var m = Math.floor(sec / 60);
        var s  = sec % 60;
        return (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
      }
    
      theSound.on("timeupdate", function() {
        var currentPos = theSound[0].currentTime; //Get currenttime
        var maxduration = theSound[0].duration; //Get video duration
        var percentage = 100 * currentPos / maxduration; //in %
        $('.timeBar').css('width', percentage + '%');
        $("#getTime").html(convertSeconds(Math.floor(theSound[0].duration)));
        $('#goTime').html(convertSeconds(Math.floor(theSound[0].currentTime)));
      });
    
      $("#playIt").click(function(event) {
        if (!isLoaded) {
          theSound.trigger('load');
          setTimeout(startBuffer, 500);
          isLoaded = true;
        }
    
        if (!isPlaying) {
    
          theSound.trigger('play');
    
          $("#playIt").find(allIcons).removeClass("fa-play");
          $("#playIt").find(allIcons).addClass("fa-pause");
    
          isPlaying = true;
    
        } else {
    
          theSound.trigger('pause');
    
          $("#playIt").find(allIcons).removeClass("fa-pause");
          $("#playIt").find(allIcons).addClass("fa-play");
    
          isPlaying = false;
    
        }
      });
    
      $("#stepFive").click(function() {
        var currentPos = theSound[0].currentTime + 5;
        theSound[0].currentTime = currentPos;
      });
    
    
      $("#stepFiveback").click(function() {
        var currentPos = theSound[0].currentTime - 5;
        theSound[0].currentTime = currentPos;
      });
    
      $('.progressBar').mousedown(function(e) {
        timeDrag = true;
        updatebar(e.pageX);
      });
    
      $(document).mouseup(function(e) {
        if (timeDrag) {
          timeDrag = false;
          updatebar(e.pageX);
        }
      });
      $(document).mousemove(function(e) {
        if (timeDrag) {
          updatebar(e.pageX);
        }
      });
    
      //update Progress Bar control
      var updatebar = function(x) {
        var progress = $('.progressBar');
        var maxduration = theSound[0].duration; //Video duraiton
        var position = x - progress.offset().left; //Click pos
        var percentage = 100 * position / progress.width();
    
        //Check within range
        if (percentage > 100) {
          percentage = 100;
        }
        if (percentage < 0) {
          percentage = 0;
        }
    
        //Update progress bar and video currenttime
        $('.timeBar').css('width', percentage + '%');
        theSound[0].currentTime = maxduration * percentage / 100;
      };
    
      //loop to get HTML5 video buffered data
      var startBuffer = function() {
    
        var maxduration = $("#firstTrack")[0].duration;
        var currentBuffer = $("#firstTrack")[0].buffered.end(0);
        var percentage = 100 * currentBuffer / maxduration;
        $('.bufferBar').css('width', percentage + '%');
    
        //re-loop if not entierely buffered
        if (currentBuffer < maxduration) {
          setTimeout(startBuffer, 500);
        }
    
      };
    
    });
    @charset "utf-8";
    
    /*head*/
    
    html,
    html * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    body {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: #1e1f1f;
      max-height: 100vh;
      /* change here */
    }
    
    
    /* -- */
    
    .noPad {
      padding: 0;
    }
    
    .playBar {
      transition: all 0.5s ease;
      height: 10px;
      background-color: rgba(186, 44, 44, 0.59);
      /*border: 1.5px;*/
      /*border-color: black;*/
      /*border-style: inset;*/
      opacity: 0.85;
      width: 0;
    }
    
    #audioCtrl>div {
      margin: 0;
      padding: 0;
    }
    
    .progressBar {
      position: relative;
      width: 100%;
      height: .4em;
      backgroud-color: #474848;
      color: #474848;
      scroll-behavior: smooth;
      border: solid;
      border-color: #474848;
      border-width: 1px;
      border-radius: 5px;
    }
    
    .timeBar {
      transition: all 0.5s ease;
      position: absolute;
      top: 0;
      left: 0;
      width: 0;
      height: 100%;
      background-color: #8c8d8e;
      border-radius: 5px;
    }
    
    .bufferBar {
      position: absolute;
      top: 0;
      left: 0;
      width: 0;
      height: 100%;
      background-color: #474949;
      opacity: 0.5;
      border-radius: 5px;
    }
    
    
    /* -- */
    
    .row {
      /* background-color: #535252; */
      border-radius: 10px;
    }
    
    .img-container img {
      margin-top: 10em;
      border-radius: 15px;
      height: 22em;
    }
    
    .navigation {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .info1 {}
    
    .title {
      font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, "sans-serif";
      font-size: 1.7em;
      margin: 0;
      padding-bottom: .4em;
      margin-left: .2em;
      color: #f1f1f1;
    }
    
    .time-btn {
      float: right;
      margin-top: .3em;
      background-color: #1E1F1F;
      color: aliceblue;
      border: 0;
      font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
      font-size: 1em;
      margin-right: .3em;
    }
    
    .time-btn2 {
      margin-top: .3em;
      background-color: #1E1F1F;
      color: aliceblue;
      border: 0;
      font-family: Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
      font-size: 1em;
      margin-left: .2em;
    }
    
    .btn {
      background-color: #1e1f1f;
      color: #D7D7D7;
      border: 0;
      font-size: 2.2em;
      padding: .3em .7em;
    }
    
    .btn-big {
      color: #FFFFFF;
      font-size: 2.4em;
    }
    
    .btn:focus {
      border: 0;
    }
    
    .scrollformore {
      color: #FFFFFF;
      font-family: "Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, "sans-serif";
      font-size: 1em;
      margin-top: 2em;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css" />
    
    <div class="container-fluid">
      <audio id="firstTrack" width="100%" preload="none">
      <source src="https://www.bensound.com/bensound-music/bensound-ukulele.mp3" type="audio/mpeg" />
      </audio>
      <div class="img-container"><img src="https://www.bensound.com/bensound-img/ukulele.jpg" alt="cover"></div>
      <h2 class="title info1">Ukulele</h2>
      <div class="row" id="audioCtrl">
        <div class="col-xs-3 progressBar">
          <div class="bufferBar"></div>
          <div class="timeBar"></div>
        </div>
        <div class="col-xs-3"><button class="time-btn info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="getTime"><div class="durationTime">00:00</div></span></i></button></div>
        <div class="col-xs-3"><button class="time-btn2 info1" type="timebar"> <i class="fas fa-refresh"> <span class="hidden-xs" id="goTime"><div class="currentTime">00:00</div></span></i></button></div>
        <div class="navigation">
          <div class="col-xs-3"><button class="btn btn-default blackb" id="stepFiveback" type="button"> <i class="fa fa-backward"> <span class="hidden-xs"></span></i></button></div>
          <div class="col-xs-3"><button class="btn btn-default blackb btn-big" id="playIt" type="button"> <i class="fa fa-play"> </i></button></div>
          <div class="col-xs-3"><button class="btn btn-default blackb" id="stepFive" type="button"> <i class="fa fa-forward"> <span class="hidden-xs"></span></i></button></div>
        </div>
      </div>
    </div>
    </div>