Force cued YouTube videos to play on sync
This commit is contained in:
+20
-4
@@ -324,10 +324,26 @@ async function ensureYoutubePlayer() {
|
||||
return youtubePlayer;
|
||||
}
|
||||
|
||||
function requestYoutubePlayback(player) {
|
||||
function requestYoutubePlayback(player, videoId, position) {
|
||||
const startedAt = Date.now();
|
||||
|
||||
for (const delay of [0, 150, 750, 1500, 3000, 5000]) {
|
||||
setTimeout(() => {
|
||||
if (desiredYoutubePlaying) player.playVideo();
|
||||
if (!desiredYoutubePlaying || currentYoutubeVideoId !== videoId) return;
|
||||
|
||||
const playerState = player.getPlayerState?.();
|
||||
if (playerState === YT.PlayerState.PLAYING) return;
|
||||
|
||||
const elapsed = Math.max(0, (Date.now() - startedAt) / 1000);
|
||||
const nextPosition = Math.max(0, position + elapsed);
|
||||
const loadedVideoId = player.getVideoData?.().video_id;
|
||||
if (
|
||||
loadedVideoId !== videoId ||
|
||||
[YT.PlayerState.UNSTARTED, YT.PlayerState.CUED, YT.PlayerState.ENDED].includes(playerState)
|
||||
) {
|
||||
player.loadVideoById(videoId, nextPosition);
|
||||
}
|
||||
player.playVideo();
|
||||
}, delay);
|
||||
}
|
||||
}
|
||||
@@ -452,7 +468,7 @@ async function applyWatchState(state, { suppressEvents = true } = {}) {
|
||||
if (shouldPlay) {
|
||||
const sameVideo = player.getVideoData?.().video_id === currentYoutubeVideoId;
|
||||
const playerState = player.getPlayerState?.();
|
||||
if (sameVideo) {
|
||||
if (sameVideo && ![YT.PlayerState.UNSTARTED, YT.PlayerState.CUED].includes(playerState)) {
|
||||
player.seekTo(position, true);
|
||||
} else {
|
||||
player.loadVideoById(currentYoutubeVideoId, position);
|
||||
@@ -460,7 +476,7 @@ async function applyWatchState(state, { suppressEvents = true } = {}) {
|
||||
if (playerState !== YT.PlayerState.PLAYING) {
|
||||
player.playVideo();
|
||||
}
|
||||
requestYoutubePlayback(player);
|
||||
requestYoutubePlayback(player, currentYoutubeVideoId, position);
|
||||
} else {
|
||||
if (player.getVideoData?.().video_id !== currentYoutubeVideoId) {
|
||||
player.cueVideoById(currentYoutubeVideoId, position);
|
||||
|
||||
Reference in New Issue
Block a user