I want to display segments of YouTube videos to end users. I currently use the YouTube IFrame API to render the videos like in the below code.
However, once the segment is over, the iframe renders related YouTube videos. Is it possible to let the end-user replay the video segment? Or is there a better solution to render segments of a Youtube video?
Current code:
The below code displays the portion of a YouTube video from 0 to 6 seconds.
<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>
You need to add more code in order to loop the video.
Here is the code:
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);
}
}
Here is the jsfiddle I've made.