简体   繁体   English

使用javascript解析并显示HTML音频当前时间

[英]Parsing and showing HTML audio current time with javascript

I'm working on a plain JavaScript + HTML audio player and at this time I want to build a interface that show the current time of the audio in the form "MM:SS". 我正在使用普通的JavaScript + HTML音频播放器,目前我想构建一个界面,以“ MM:SS”的形式显示音频的当前时间。 For what I could search the HTML Audio/Video DOM Reference has only one native function - audio|video.currentTime - that return the current audio time in seconds with a large decimal precision. 对于我可以搜索的内容,“ HTML音频/视频DOM参考”只有一个本机函数audio|video.currentTime以秒为单位返回当前音频时间,具有十进制的大精度。

In order to do this I code: 为了做到这一点,我编写代码:

HTML HTML

<audio id='audio' src="http://www.stephaniequinn.com/Music/Canon.mp3" controls></audio>
<div id="timer">00:00</div>

JavaScript 的JavaScript

var audio = document.getElementById('audio'),
      timer = document.getElementById('timer');

var update = setInterval(function() {

  timer.innerHTML = audio.currentTime;
}, 10);

I tried a bunch of thing but I could not format the output the way I wanted. 我尝试了一堆东西,但无法按照自己的方式格式化输出。 Hope some of you guys can bring some light on this. 希望你们中的一些人能对此有所启发。

Codepen sample Codepen样本

Working edited CodePen 正在编辑的CodePen

Just needed a little math! 只是需要一点数学! JS below: JS下面:

var update = setInterval(function() {
      var mins = Math.floor(audio.currentTime / 60);
      var secs = Math.floor(audio.currentTime % 60);
      if (secs < 10) {
        secs = '0' + String(secs);
      }
      timer.innerHTML = mins + ':' + secs;
    }, 10);

I think this is the most elegent way: 我认为这是最优雅的方式:

var seconds = audio.currentTime % 60;
var minutes = Math.floor(audio.currentTime / 60);

timer.innerHTML = ('0' + minutes).substr(-2) + ':' + ('0' + seconds).substr(-2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM