背景
我正在尝试将视频集成到幻灯片展示应用程序中。我已经在学生端禁用了控件,并将播放/暂停按钮连接到YouTube API,这样当点击按钮时,通过推动器触发一个事件,视频会在老师的屏幕和学生的屏幕上同时开始播放。
困难
问题出现在当其中一个用户的网络连接较慢时。如果老师的网络速度比学生快,则视频将不同步。
我的解决方案
我有一个函数,使用YouTube API来控制视频的播放和暂停。
/**
*
*/
togglePlay: function(){
var videoId = this.videoId;
if (this.isPlaying) {
this.players[videoId].pauseVideo(); // Pauses the video
this.isPlaying = false;
} else {
this.players[videoId].playVideo(); // Starts the video
this.isPlaying = true;
}
},
在视频对象中添加了一个onStateChange
事件监听器,当视频播放/暂停/缓冲时触发。该事件会被发送到该函数。
/**
*
*/
emittStateChange: function(e){
switch(e.data) {
// if the teachers video is...
case 1: // playing
pusher.channel4.trigger('client-youtube-triggered', {
videoId: youtube.videoId,
status: 1, // start the students video
});
break;
case 2: // paused
pusher.channel4.trigger('client-youtube-triggered', {
videoId: youtube.videoId,
status: 2, // pause the students video
});
break;
case 3: // buffering
pusher.channel4.trigger('client-youtube-triggered', {
videoId: youtube.videoId,
status: 2, // pause the students video
});
}
},
当老师按下播放键时,视频开始播放,并触发了一个播放事件,该事件被发送到上述函数。该函数向学生的浏览器发送一个状态为1的推送事件,表示播放视频。此事件由以下函数接收:
/**
*
*/
receiveStateChange: function(data){
this.videoId = data.videoId;
switch(data.status) {
// if the teachers video is...
case 1: // playing
this.isPlaying = false;
this.togglePlay();
break;
case 2: // paused
this.isPlaying = true;
this.togglePlay();
break;
case 2: // buffering
this.isPlaying = true;
this.togglePlay();
}
},
我理解的问题及需求:
- 老师的视频停止后,学生的视频还没有完全缓冲好就会再次触发onStateChange事件并发送给学生。
- 这将导致学生的视频停止播放,现在两个视频都暂停了。
当学生的视频正在缓冲时,我只想临时暂停老师的视频,直到学生的视频开始播放,然后同时播放两个视频。 我不知道如何打破这个循环,以避免两个视频都被暂停。