我正在研究一个在负载下寻找指定时间并开始循环播放视频短片段的播放器。这将首先用作背景,但是,有一个带有样式播放按钮的叠加层,可以提供视频详细信息。点击该按钮后,视频将重置为开始,取消静音和播放。我有一切工作,除了当视频重置时它会打破onPlayerStateChange事件,这意味着视频将无法检测到结束并重置它的循环。我相信这取决于我如何更改playerVars,访问src属性并更改' controls = 0'到'控制= 1'。有没有更正确的方法来更改这些不会破坏玩家事件的属性?我在这里设置了一个小提琴:https://jsfiddle.net/BearSkull/uqje4793/
//This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//This function creates an <iframe> (and YouTube player)
//after the API code downloads.
var youTubeId = '-hTVNidxg2s';
var startTime = 85; //start time in seconds
var stopTime = 95; //end time in seconds
var playInterval = (stopTime - startTime) * 1000; //converts to milliseconds
var ratio = 16 / 9; //YT player ratio
var playerWidth = jQuery(window).width();
var playerHeight = Math.ceil(playerWidth / ratio);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('youtube-player', {
height: playerHeight,
width: playerWidth,
videoId: youTubeId,
playerVars: {
'controls': 0,
'showinfo': 0
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
var intervalCallbackId
var loopFunction = function() {
intervalCallbackId = setInterval(playerSeek, playInterval);
};
function playerSeek() {
player.seekTo(startTime);
};
//The API will call this function when the video player is ready.
var started = false;
function onPlayerReady(event) {
jQuery('.hero-background-image').delay(1500).fadeOut(1000);
if (started === false) {
player.seekTo(startTime).mute().playVideo();
loopFunction(event);
started = true;
} else {
player.seekTo(0).unMute().setVolume(100).playVideo();
}
}
//Play Button Click Function
jQuery(".desktop-play-btn").on('click', function() {
var src = jQuery('#youtube-player').attr('src');
jQuery('#youtube-player').attr('src', src.replace("controls=0", "controls=1"));
clearInterval(intervalCallbackId);
jQuery('#player-overlay').fadeOut(1000);
jQuery('#hero-youtube-video, #youtube-player').css({
'z-index': '99'
});
player.seekTo(0).unMute().setVolume(100).playVideo();
});
//The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
player.seekTo(startTime).mute().playVideo();
loopFunction(event);
}
}