问题
Is there a way to use the Youtube API to play a video until a certain point in the video and then pause it?
回答1:
I've modified the code from the YouTube Player API Reference for iframe Embeds to pause play after a certain number of seconds.
Demo
The code works by waiting for the onPlayerStateChange
event. When the event fires, it checks the event to see if it's a PLAYING
event. If it is, it calculates the remaining time from the current time (getCurrentTime()
method) to the desired pause point (hardcoded as the stopPlayAt
variable). It sets a Javascript timer to wait that difference and then pass the API a command to pause the video.
回答2:
You can use the command cueVideoById
in Object syntax to achieve this.
See here: https://developers.google.com/youtube/iframe_api_reference#cueVideoById
This is the way it should look like to start a video like this.
//Minimal Example
player.cueVideoById({videoId:String, endSeconds:Number});
player.playVideo();
EDIT: The above sample stops the video. If you want to pause it, a little more action is required by the JavaScript code.
In detail, you have to poll for the right time.
function checkTime() {
if ( player.getCurrentTime() == finishTime )
player.pauseVideo()
else
setInterval(checkTime, 500);
}
checkTime();
Or keep track of the time in JS:
var duration = finishTime - player.getCurrentTime();
player.playVideo()
setInterval("player.pauseVideo();", duration*1000);
来源:https://stackoverflow.com/questions/14152415/use-youtubeapi-to-play-youtube-video-until-a-particular-time-and-pause