我想向最终用户显示 YouTube 视频片段。我目前使用 YouTube IFrame API 来渲染视频,如下面的代码所示。
但是,一旦片段结束,iframe 就会呈现相关的 YouTube 视频。是否可以让最终用户重播视频片段?或者有更好的解决方案来渲染 Youtube 视频的片段吗?
当前代码:
下面的代码显示 YouTube 视频中 0 到 6 秒的部分。
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'iuig147bQnY',
playerVars: {
start: 0,
end: 6,
controls: 0,
fs: 0,
playsinline: 1,
modestbranding: 1,
rel: 0,
loop:1
},
events: {
}
});
}
</script>
您需要添加更多代码才能循环播放视频。
这是代码:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId: 'iuig147bQnY',
height: '390',
width: '640',
playerVars: {
mute: 1, // (Required for autoplay the video).
autoplay: 1,
start: 0,
end: 6,
controls: 0,
fs: 0,
playsinline: 1,
modestbranding: 1,
rel: 0,
loop: 1,
enablejsapi: 1,
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
// When the video ends, it will play again.
// See: https://developers.google.com/youtube/iframe_api_reference?hl=en#Events
// Using ths way of loop the video it will not show related videos, but
// it will show loading a little bet the video.
if (event.data == YT.PlayerState.ENDED) {
player.seekTo(0);
}
}
这是我制作的jsfiddle。