Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

javascript - Start HTML5 video at a particular position when loading?

I need HTML5 video to start at certain point. Let's say at time 50 seconds onward.

I tried but its not working as expected. is there something i am doing wrong?

Here is the code:

   <video id="vid1" width="640" height="360">
       <source src="file.webm" type="video/webm" /> 
       Your browser does not support the video tag.
   </video>
   <script>
       document.getElementById('vid1').currentTime = 50;
   </script> 

When the page loads, it just starts playing from beginning. However if I call this during playback like after some time, it works fine. Is there anything I am missing?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to wait until the browser knows the duration of the video before you can seek to a particular time. So, I think you want to wait for the 'loadedmetadata' event something like this:

document.getElementById('vid1').addEventListener('loadedmetadata', function() {
  this.currentTime = 50;
}, false);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...