我有一个使用YouTubeAPI(iframe)播放的视频。在单击控件以启动视频之前,图像将代替视频。图像与视频交换,视频播放。当视频结束时,过程反转。问题是我可以使用自定义控件让视频重新启动第二次。这是我的代码......
<script src="https://www.youtube.com/iframe_api"></script>
<div class="video" id="vid">
<a class="video-control" href="#"></a>
<img id="video-front" src="<?= get_field('video_image') ?>" class="img-responsive" alt="">
<div class="video-container">
<iframe id="player" type="text/html"
src="http://www.youtube.com/embed/G5M721A0b_Q?enablejsapi=1&rel=0&autoplay=1"
frameborder="0"></iframe>
</div>
</div>
<script>
(function($){
//move vid control
vidControlHeight();
$('.video-control').css('left', '-' + wControl + 'px');
$('.video-control').on('click', function(event){
event.preventDefault();
$('#video-front').hide();
$('.video-container').show();
onYouTubeIframeAPIReady();
})
})(jQuery);
function vidControlHeight(){
var hBox = $('#vid').height() / 2,
hControl = $('.video-control').height() / 2,
boxPosition = hBox - hControl;
wControl = $('.video-control').width() / 2;
$('.video-control').css({'left':'-' + wControl + 'px', 'top': boxPosition + 'px'});
}
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if(event.data == YT.PlayerState.ENDED){
$('#video-front').show();
$('.video-container').hide();
}
}
</script>
如何让视频重播第二次,第三次,第四次?
答案 0 :(得分:5)
虽然它正在调用播放,但视频并没有将自己重新设置为开始播放。我不得不设置
player.seekTo(0);
在onPlayerStateChange()函数中。
function onPlayerStateChange(event) {
if(event.data == YT.PlayerState.ENDED){
player.seekTo(0);
$('#video-front').show();
$('.video-container').hide();
}
}
https://developers.google.com/youtube/js_api_reference#seekTo
答案 1 :(得分:0)
您可以添加loop
参数:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
},
loop: 1
});
}
https://developers.google.com/youtube/player_parameters#loop
或者,如果状态为onPlayerStateChange
,那么您可以查看0
视频结束时的状态,只需致电event.target.playVideo();