Skip to content

Instantly share code, notes, and snippets.

@ysawa
Created November 4, 2017 03:47
Show Gist options
  • Save ysawa/85c657de3ac98439e7dbac3f4a866489 to your computer and use it in GitHub Desktop.
Save ysawa/85c657de3ac98439e7dbac3f4a866489 to your computer and use it in GitHub Desktop.
Simple WebRTC Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
video {
width: 320px;
height: 240px;
}
</style>
</head>
<body>
<h1>WebRTC Local Connections</h1>
<p>Video stream created by getUserMedia will be shown in the left video tag.</p>
<p>The stream will be sent to the right video tag over RTCPeerConnection.</p>
<video id="local-video" autoplay></video>
<video id="remote-video" autoplay></video>
<script>
var localVideo = document.querySelector('#local-video');
var remoteVideo = document.querySelector('#remote-video');
var offerOptions = {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
};
var setStreamToVideo = function (stream, video) {
if (window.URL) {
video.src = window.URL.createObjectURL(stream);
} else {
video.src = stream;
}
};
navigator.getUserMedia({video: true, audio: false}, function (stream) {
var configuration = null;
var connection1 = new RTCPeerConnection(configuration);
var connection2 = new RTCPeerConnection(configuration);
var getOtherConnection = function (connection) {
return (connection === connection1) ? connection2 : connection1;
};
var onIceCandidate = function (connection, event) {
if (event.candidate) {
getOtherConnection(connection).addIceCandidate(
event.candidate
);
}
};
setStreamToVideo(stream, localVideo);
connection2.onaddstream = function (e) {
console.log('connection2.onaddstream');
setStreamToVideo(e.stream, remoteVideo);
};
connection1.onicecandidate = function(e) {
onIceCandidate(connection1, e);
};
connection2.onicecandidate = function(e) {
onIceCandidate(connection2, e);
};
connection1.addStream(stream);
connection1.createOffer(offerOptions).then(function (offer) {
console.log('connection1.createOffer');
connection1.setLocalDescription(offer);
connection2.setRemoteDescription(offer);
connection2.createAnswer().then(function (answer) {
console.log('connection2.createAnswer');
connection1.setRemoteDescription(answer);
connection2.setLocalDescription(answer);
})
})
}, console.error)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment