I'm trying to make a web app with youtube iframe api, using socket.io. The goal of the application is to watch and control youtube videos on sync, i was able achieve this with custom controls with the player functions.
But I want to make this happen with the native youtube controls, so I found that it can be done by listening to the events using the onPlayerStateChange() function,
Client:
const onPlayerStateChange = event => {
console.log(event.data);
switch (event.data) {
case 1:
playVid();
break;
case 2:
pauseVid();
break;
};
const playVid = () => {
console.log("play");
socket.emit(
"send-data",
{
state: "play",
time: player.getCurrentTime(),
},
room
);
};
const pauseVid = () => {
console.log("pause");
socket.emit(
"send-data",
{
state: "pause",
time: player.getCurrentTime(),
},
room
);
};
socket.on("recv-data", data => {
if (data.state == "play") {
if (Math.abs(data.time - player.getCurrentTime()) > 1)
player.seekTo(data.time);
player.playVideo();
} else if (data.state == "pause") {
player.pauseVideo();
}
});
Server:
io.on("connection", socket => {
socket.on("send-data", (data, room) => {
io.to(room).emit("recv-data", data);
});
socket.on("join-room", room => {
socket.join(room);
});
});
When more than one player gets connected in a room playing the video, at some point, the player state gets messed up having a series of plays and pauses, so much that the screen freezes.
index.js:107 play
index.js:90 2
index.js:119 pause
index.js:90 1
index.js:107 play
index.js:90 2
index.js:119 pause
index.js:90 1
index.js:107 play
index.js:90 2
index.js:119 pause
index.js:90 1
index.js:107 play
index.js:90 2
index.js:119 pause
index.js:90 1
and goes on...
What Am I doing wrong? and how to correct this?