如何在多个客户端上同步播放 YouTube 视频?

2022-01-06 00:00:00 youtube real-time jquery php ajax

我希望了解如何构建允许多个用户在他们的计算机上同步观看同一个 YouTube 视频的网络应用.例如,synchtube.com 或 watch2gether.com

I'm looking to understand how to build a web app that allows multiple users to view the same YouTube video in sync on their computers. For example, synchtube.com or watch2gether.com

我正在寻找一种简单的方法,可以使用诸如 PHPjQueryApache 等常用技术来实现.我目前正在考虑轮询(或彗星长轮询,但需要更复杂的服务器设置,我希望避免),类似于 Ajax 聊天应用程序的实现方式 - 即客户端不断检查与服务器查看正在播放的视频.但是,我怀疑这里会有延迟问题,因此视频不会完全同步.我还想不出更好的方法.

I'm seeking a simple approach that can be implemented using common technologies such as PHP, jQuery and Apache. I'm currently thinking along the lines of polling (or comet long polling but that requires more complex server setup which I hope to avoid), similar to how Ajax chat apps are implemented - that is clients continuously check with the server to see which video is playing. However, I suspect there will be latency issues here so videos will not be completely in sync. I can't think of a better approach yet.

对于开发人员社区,我们非常感谢对方法或代码片段的任何帮助!

To fellow developer community, any help on the methodology or code snippets are hugely appreciated!

推荐答案

以下是使用 WebSockets 和 node.js 保持视频同步的示例:http://softwareas.com/video-sync-with-websocket-and-node

Here's an example of keeping videos in sync using WebSockets and node.js: http://softwareas.com/video-sync-with-websocket-and-node

我知道您不想使用这项技术,这只是展示您可以做什么以及如何做的一个很好的起点.

既然您想使用 PHP 并保持简单,那么您最好的解决方案是将实时通信层(用于保持用户视频同步)外包给托管服务,例如 Pusher,我为他工作.这意味着您不需要维护持久连接,并且您可以使用 Pusher 在用户/客户端之间传递有关视频状态的实时事件.

Since you want to use PHP and keep things simple then your best solution is to outsource the realtime communications layer (used to keep the user videos in sync) to a hosted service such as Pusher, who I work for. This means you don't need to maintain the persistent connection and you can use Pusher to deliver realtime events about the video states between users/clients.

如果您想使用 YouTube 视频,并且 HTML5 并不总是可用,那么您需要使用 播放器 API.我看不到类似的 timeupdated 事件(在 HTML5 视频中可用),因此您可能需要定期检查视频时间(请参阅 播放器状态 API 部分.您可以注册状态更改事件,以便了解用户何时暂停、停止视频等.

If you want to use YouTube videos, and HTML5 isn't always going to be available, then you'll need to use the Player API. I can't see a similar timeupdated event (available in HTML5 video) so you might need to periodically check the video time (see player status API section. You can register for state change events so you know when a user pauses, stops a video etc.

@rob-w 的评论为使用 YouTube API 提供了一些很好的见解.

@rob-w's comment provides some good insight into using the YouTube API.

注意:这实际上可能会成为一篇非常有趣的博客文章,所以如果您有兴趣,请告诉我,我会看看我能做些什么.

相关文章