Last active
April 22, 2019 18:11
-
-
Save Marcin648/d86bdcb8a8ee0bc7bf9f3dea4d5a2237 to your computer and use it in GitHub Desktop.
Synchronizes video on the page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Marcin648 2019 | |
VideoJS WebRTC Sync | |
*/ | |
function loadScript(url, callback){ | |
var head = document.head; | |
var script = document.createElement('script'); | |
script.type = 'text/javascript'; | |
script.src = url; | |
script.onreadystatechange = callback; | |
script.onload = callback; | |
head.appendChild(script); | |
}; | |
channel = null; | |
vjs = null; | |
eventIgnoreFlag = false; | |
function vjsSyncPlay(){ | |
if(eventIgnoreFlag){ | |
eventIgnoreFlag = false; | |
return; | |
} | |
console.log("Send sync PLAY"); | |
msg = {"action": "play"}; | |
channel.send(JSON.stringify(msg)); | |
} | |
function vjsSyncPause(){ | |
if(eventIgnoreFlag){ | |
eventIgnoreFlag = false; | |
return; | |
} | |
console.log("Send sync PAUSE"); | |
msg = {"action": "pause"}; | |
channel.send(JSON.stringify(msg)); | |
} | |
function vjsSyncTime(){ | |
if(eventIgnoreFlag){ | |
eventIgnoreFlag = false; | |
return; | |
} | |
console.log("Send sync TIME"); | |
msg = { | |
"action": "sync", | |
"time": vjs.currentTime() | |
}; | |
channel.send(JSON.stringify(msg)); | |
} | |
loadScript("https://cdn.webrtc-experiment.com/DataChannel.js", function(){ | |
vjs = videojs.getAllPlayers()[0]; | |
if(typeof(vjs) == "undefined"){ | |
console.log("ERROR Player not found!"); | |
return; | |
} | |
console.log("Script loaded!"); | |
channel = new DataChannel("videosync-asdf"); | |
channel.onerror = function(event) { console.log(event); } | |
channel.onclose = function(event) { console.log(event); } | |
channel.onopen = function(userid) { console.log("Connected"); } | |
channel.onmessage = function(message, userid, latency){ | |
console.log("[" + latency + "] Revieve from " + userid + ": " + message); | |
msg = JSON.parse(message); | |
switch(msg["action"]){ | |
case "play": | |
eventIgnoreFlag = true; | |
vjs.play(); | |
break; | |
case "pause": | |
eventIgnoreFlag = true; | |
vjs.pause();; | |
break; | |
case "sync": | |
eventIgnoreFlag = true; | |
vjs.currentTime(msg["time"]); | |
break; | |
}; | |
}; | |
vjs.on("play", vjsSyncPlay); | |
vjs.on("pause", vjsSyncPause); | |
vjs.on("seeking", vjsSyncTime); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment