设置页面加载时音频对象的当前时间

时间:2018-07-11 16:13:06

标签: javascript html5 html5-audio

当加载html页面时,如何设置音频对象的当前时间?这是我目前正在做的事情:

var a = document.getElementById("myAudio");

a.addEventListener("timeupdate", function() {
    console.log(this.currentTime);
    // do other stuff like display the current time 
}

var isCurrentTimeSetOnStartup = false;
a.addEventListener("canplay", function() {
    if (isCurrentTimeSetOnStartup == false){
        this.currentTime = startTime;
        isCurrentTimeSetOnStartup = true;
    }
});
我认为这很丑。如果我没有isCurrentTimeSetOnStartup保护,那么这两个事件会互相触发。

1 个答案:

答案 0 :(得分:1)

您可以将脚本放置在<body>标签的底部,然后使用以下代码设置音频源的currentTime


let a = document.querySelector('#myAudio');
let startTime = 2;


a.addEventListener('canplay', function handler() {
  // Time in seconds
  this.currentTime = startTime; 
  // Remove the event listener
  this.removeEventListener('canplay', handler);
});


a.addEventListener('timeupdate', function() {
  //Time in seconds
  console.log(this.currentTime);
});

// Play on DOM-Load
a.play();
<!--http://picosong.com/wwPMj/-->
<audio id="myAudio" controls>
  <source src="https://www.computerhope.com/jargon/m/example.mp3" type="audio/mpeg">
  Your browser does not support HTML5 video.
</audio>