如何使用JavaScript在自定义html5音频播放器中计算剩余时间?

时间:2018-08-09 11:49:12

标签: javascript html5 audio html5-audio audio-player

我找到了一个不错的自定义HTML5音频播放器,并根据自己的需要成功地对其进行了重新设计。一切正常,只是没有显示“剩余”时间(实际上还剩下多少时间来跟踪结束时间)。

我想在不更改原始脚本的情况下添加剩余时间的计算,可以吗?

[

function calculateTotalValue(length) {
  var minutes = Math.floor(length / 60),
    seconds_int = length - minutes * 60,
    seconds_str = seconds_int.toString(),
    seconds = seconds_str.substr(0, 2),
    time = minutes + ':' + seconds

  return time;
}

function calculateCurrentValue(currentTime) {
  var current_hour = parseInt(currentTime / 3600) % 24,
    current_minute = parseInt(currentTime / 60) % 60,
    current_seconds_long = currentTime % 60,
    current_seconds = current_seconds_long.toFixed(),
    current_time = (current_minute < 10 ? "0" + current_minute : current_minute) + ":" + (current_seconds < 10 ? "0" + current_seconds : current_seconds);

  return current_time;
}

CodePen(原始播放器源代码)

1 个答案:

答案 0 :(得分:0)

您想要的非常简单,您无需更改很多代码,而只需添加两行。

在“ initProgressBar()”函数中,只需添加这两行代码

//计算剩余时间

var rem_time=length-current_time;
 jQuery(".rem-time").html(calculateCurrentValue(rem_time));

// HTML显示剩余时间(将其添加到HTML)

 <small style="float: left; position: relative; left: 15px;" class="rem-time"></small>

第一行只是获取总秒数,代码中已经提供了“长度”和“ current_time”,因此我只是在使用它们,没有新内容。

在第二行中,我将剩余时间转换为可读格式,再次使用一个已经可用的函数“ calculateCurrentValue()”并用剩余时间设置HTML元素。

最后是显示剩余时间的HTML元素。

您也可以看看我为更好理解而做的CodePen

在此处添加完整代码以确保其始终可用

function calculateTotalValue(length) {
  var minutes = Math.floor(length / 60),
    seconds_int = length - minutes * 60,
    seconds_str = seconds_int.toString(),
    seconds = seconds_str.substr(0, 2),
    time = minutes + ':' + seconds

  return time;
}

function calculateCurrentValue(currentTime) {
  var current_hour = parseInt(currentTime / 3600) % 24,
    current_minute = parseInt(currentTime / 60) % 60,
    current_seconds_long = currentTime % 60,
    current_seconds = current_seconds_long.toFixed(),
    current_time = (current_minute < 10 ? "0" + current_minute : current_minute) + ":" + (current_seconds < 10 ? "0" + current_seconds : current_seconds);

  return current_time;
}
var prevcurrentime=0;
function initProgressBar() {
  var player = document.getElementById('player');
  var length = player.duration
  var current_time = player.currentTime;

  // calculate total length of value
  var totalLength = calculateTotalValue(length)
  jQuery(".end-time").html(totalLength);

  // calculate current value time
  var currentTime = calculateCurrentValue(current_time);
  
  jQuery(".start-time").html(currentTime);
  //checking if the current time is bigger than the previous or else there will be sync different between remaining and current
  if(currentTime>prevcurrentime){
  //calculate the remaining time
  var rem_time=length-current_time;
 jQuery(".rem-time").html(calculateCurrentValue(rem_time));
  }
  //setting the previouscurrent time to this current time
  prevcurrentime=currentTime;
  //progress bar calculation
  var progressbar = document.getElementById('seekObj');
  progressbar.value = (player.currentTime / player.duration);
  progressbar.addEventListener("click", seek);

  if (player.currentTime == player.duration) {
    $('#play-btn').removeClass('pause');
  }

  function seek(evt) {
    var percent = evt.offsetX / this.offsetWidth;
    player.currentTime = percent * player.duration;
    progressbar.value = percent / 100;
  }
};

function initPlayers(num) {
  // pass num in if there are multiple audio players e.g 'player' + i

  for (var i = 0; i < num; i++) {
    (function() {

      // Variables
      // ----------------------------------------------------------
      // audio embed object
      var playerContainer = document.getElementById('player-container'),
        player = document.getElementById('player'),
        isPlaying = false,
        playBtn = document.getElementById('play-btn');

      // Controls Listeners
      // ----------------------------------------------------------
      if (playBtn != null) {
        playBtn.addEventListener('click', function() {
          togglePlay()
        });
      }

      // Controls & Sounds Methods
      // ----------------------------------------------------------
      function togglePlay() {
        if (player.paused === false) {
          player.pause();
          isPlaying = false;
          $('#play-btn').removeClass('pause');

        } else {
          player.play();
          $('#play-btn').addClass('pause');
          isPlaying = true;
        }
      }
    }());
  }
}

initPlayers(jQuery('#player-container').length);
html {
  height: 100%;
  display: table;
  margin: auto;
}

body {
  height: 100%;
  display: table-cell;
  vertical-align: middle;
  background: yellow;
}

.audio-player {
  background: white;
  border: 1px solid #dfdfdf;
  width: 50vw;
  text-align: center;
  display: flex;
  flex-flow: row;
  margin: 4rem 0 4rem 0;
}
.audio-player .album-image {
  min-height: 100px;
  width: 110px;
  background-size: cover;
}
.audio-player .player-controls {
  align-items: center;
  justify-content: center;
  margin-top: 2.5rem;
  flex: 3;
}
.audio-player .player-controls progress {
  width: 90%;
}
.audio-player .player-controls progress[value] {
  -webkit-appearance: none;
  appearance: none;
  background-color: white;
  color: blue;
  height: 5px;
}
.audio-player .player-controls progress[value]::-webkit-progress-bar {
  background-color: white;
  border-radius: 2px;
  border: 1px solid #dfdfdf;
  color: blue;
}
.audio-player .player-controls progress::-webkit-progress-value {
  background-color: blue;
}
.audio-player .player-controls p {
  font-size: 1.6rem;
}
.audio-player #play-btn {
  background-image: url("http://www.lukeduncan.me/images/play-button.png");
  background-size: cover;
  width: 75px;
  height: 75px;
  margin: 2rem 0 2rem 2rem;
}
.audio-player #play-btn.pause {
  background-image: url("http://www.lukeduncan.me/images/pause-button.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="audio-player">
    <div id="play-btn"></div>
    <div class="audio-wrapper" id="player-container" href="javascript:;">
      <audio id="player" ontimeupdate="initProgressBar()">
			  <source src="http://www.lukeduncan.me/oslo.mp3" type="audio/mp3">
			</audio>
    </div>
    <div class="player-controls scrubber">
      <p>Oslo <small>by</small> Holy Esque</p>
      <span id="seekObjContainer">
			  <progress id="seekObj" value="0" max="1"></progress>
			</span>
      <br>
      <small style="float: left; position: relative; left: 15px;" class="start-time"></small><br/>
      <small style="float: left; position: relative; left: 15px;" class="rem-time"></small>
      <small style="float: right; position: relative; right: 20px;" class="end-time"></small>

    </div>
    <div class="album-image" style="background-image: url('https://artwork-cdn.7static.com/static/img/sleeveart/00/051/614/0005161476_350.jpg')"></div>
  </div>