I am building a platform for multiuser simultaneous video viewing. To achieve this I am using youtubes iframe api which has a loadNewVideoById function which allows you to update the video inside the player object and therefore view a new video.
I have build my own time slider which is supposed to grab the duration from the new video and initialise the max attribute of the range slider, representing time.
Here is the function that is handling that part.
function initSliderAndTime() {
setTimeout(() => {
var durationInSeconds = player.getDuration()
$('#time-slider').attr('max', player.getDuration().toString().match(/^-?\d+(?:\.\d{0,1})?/)[0])
$('#end-time')[0].innerText = calculateTimeFormat(durationInSeconds);
}, 2000);
}
which is being called in the loadNewVideo function (not from youtube) which is being called when a user wants to view a new video.
function loadNewVideo(videoId, unMute, startSeconds) {
player.loadVideoById({videoId: videoId,
startSeconds: startSeconds | 0,
});
$('#video-input')[0].value = "https://www.youtube.com/watch?v=" + videoId;
if(unMute) {
player.unMute()
$('#mute-unmute-btn').children().removeClass('fa-volume-xmark');
$('#mute-unmute-btn').children().addClass('fa-volume-high')
}
showVideoControls();
initSliderAndTime();
forwardingInterval = setInterval(function () {
updateSliderAndTime()
}, 100);
}
If I don't set a big enough timeout the getDuration object function doesn't get loaded fast enough and the function fails.
Youtube has a OnReadyFuntion that is supposed to handle the player when it is created. Unfortunately this function doesn't get called when the player is updated, only upon creation.
How can this be reconfigured so that is executes the initSlider function when getDuration is ready.
Any help is appreciated!