Issue setting currentTime in HTML5 video

。_饼干妹妹 提交于 2019-11-27 07:37:46

问题


I have a video in the middle of my html. As you can see at first I haven't any source

<video id="videoPrincipal" src="" width="640" height="360" controls preload></video>

When I click a button I trigger a function that makes:

myVid = document.getElementById('videoPrincipal');
myVid.src = 'video.mp4';
myVid.play();
myVid.currentTime ='5';

The video starts playing correctly but I cant set the current time (and I made the same as we can see in http://www.w3schools.com/tags/av_prop_currenttime.asp)

It gives me the same error if I set the currentTime before calling the play function.

The error that shows me in the console is the following: "Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable." (in the currentTime line) but when i search this problem I cant associate with video, only with canvas.

Thanks in advance


回答1:


You don't have to wait for it to start playing, but it does have to be ready to play. There's the canplay event to do that, so something like this should work:

myVid.play();
myVid.addEventListener('canplay', function() {
    this.currentTime = 5;
});



回答2:


As above mentioned, you try to set currentTime when the video is not seekable. So, as an alternative use-case (reset time to 0 when a user click on a button, for example), you can do something like:

function resetVideo() {
  myVid.pause();
   
  if (myVid.seekable.length > 0) {
    myVid.currentTime = 0;
  }
}

Alternatively, you can also trying to reset only if the video has been played before.

function resetVideo() {
  myVid.pause();
   
  if (myVid.currentTime !== 0) {
    myVid.currentTime = 0;
  }
}



回答3:


video = document.getElementById('video');
begin_play  = 50;
play_video_first = true; //if you want to run only first time    
video.addEventListener("play", capture, false);

function capture(event) 
{
     if (event.type == "play"){
         if(play_video_first){
             play_video_first = false;
             video.currentTime = begin_play;
          }
     }
}



回答4:


You have to wait until it's ready to play,
i.e. don't expect play to be a blocking function
Change your code as follows:

myVid.play();
myVid.media.addEventListener('playing', function(){
    myVid.setCurrentTime(5);
});


来源:https://stackoverflow.com/questions/20240088/issue-setting-currenttime-in-html5-video

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!