Trying to synchronize the play/pause of the YouTube player for all the user's. I am getting the data on client side from server but its not playing the or pause the video base on that action.
What I want to achieve is that if the owner of the room plays the video it should get played for everyone
Backend WebSocket setup
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
wss.on("connection", (ws, req) => {
ws.on("message", (message) => {
console.log(wss.clients.size);
try {
const data = JSON.parse(message.toString());
console.log("Received message:", data);
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data));
}
});
} catch (error) {
console.error("Error parsing message:", error);
}
});
console.log("connected");
ws.on("close", () => {
console.log("Client disconnected");
});
});
Front end setup
const [player, setPlayer] = useState<YouTubePlayer | null>(null);
const ws = useRef<WebSocket | null>(null);
// youtube player callbacks
useEffect(() => {
if (!ws.current) {
ws.current = new WebSocket("ws://localhost:3000/");
ws.current.onopen = () => {
console.log("WS connected");
};
}
ws.current.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(data);
if (player) {
switch (data.action) {
case "play":
console.log("Playing video");
player.playVideo();
break;
case "pause":
console.log("Pausing video");
player.pauseVideo();
break;
}
} else {
console.warn("YouTube player not yet initialized");
}
};
ws.current.onclose = () => {
console.log("WS disconnected");
};
// return () => {
// if (ws.current) {
// ws.current.close();
// ws.current = null;
// }
// };
}, []);
const handlePlay = () => {
if (ws.current && ws.current?.readyState === WebSocket.OPEN) {
console.log("Sending play action");
ws.current?.send(JSON.stringify({ action: "play" }));
}
};
const handlePause = (e: YouTubeEvent) => {
if (ws.current && ws.current?.readyState === WebSocket.OPEN) {
console.log("Sending pause action");
ws.current?.send(JSON.stringify({ action: "pause" }));
}
};
const youtubePlayerOpts = {
height: "100%",
width: "100%",
playerVars: {
autoplay: 1 as 0 | 1,
// controls: isOwner ? (1 as 0 | 1) : (0 as 0 | 1),
// disablekb: isOwner ? (0 as 0 | 1) : (1 as 0 | 1),
// modestbranding: 1 as 1,
// rel: 0 as 0 | 1,
},
};
YouTube Player component
<YouTube
videoId={currentSong?.externalId}
opts={youtubePlayerOpts}
className="h-[90%] w-full"
onReady={(e) => {
setPlayer(e.target);
}}
onPlay={handlePlay}
onPause={handlePause}
/>
Tried adding player as a dependency, tried putting console logs but unable to find the problem, Sometimes it does get play but I am confuse why only sometimes, also sometimes it dont initialize the player