Javascript/HTML5:获取音频标签的当前时间 [英] Javascript/HTML5: get current time of audio tag

查看:95
本文介绍了Javascript/HTML5:获取音频标签的当前时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模板中有一个音频标签,单击按钮时需要显示它的currentTime.请在下面检查我的代码:

I have an audio tag in my template and I need to show currentTime of it on a button click. Please check my code below:

var myaudio = document.getElementsByTagName("audio")[0];
var cur_time = myaudio.currentTime;
$('#curPosition').val(cur_time);

但是在播放音频时,它总是返回0作为当前时间.有人对此有任何想法吗?

But it always returns 0 as current time while the audio is playing. Do anybody have any idea on this ?

谢谢

推荐答案

您可以尝试这样

<audio id="track" src="http://upload.wikimedia.org/wikipedia/commons/a/a9/Tromboon-sample.ogg"
       ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime) + ' / ' + Math.floor(this.duration);">
    <p>Your browser does not support the audio element</p>
</audio>
<span id="tracktime">0 / 0</span>
<button onclick="document.getElementById('track').play();">Play</button>

,或者在javascript中,您可以执行此操作

<audio id='audioTrack' ontimeupdate='updateTrackTime(this);'>
  Audio tag not supported in this browser</audio>
<script>
function updateTrackTime(track){
  var currTimeDiv = document.getElementById('currentTime');
  var durationDiv = document.getElementById('duration');

  var currTime = Math.floor(track.currentTime).toString(); 
  var duration = Math.floor(track.duration).toString();

  currTimeDiv.innerHTML = formatSecondsAsTime(currTime);

  if (isNaN(duration)){
    durationDiv.innerHTML = '00:00';
  } 
  else{
    durationDiv.innerHTML = formatSecondsAsTime(duration);
  }
}
</script>

我目前没有时间用javascript

I am currently getting time out of javascript

这篇关于Javascript/HTML5:获取音频标签的当前时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆