Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- /// SELECT DEVICES
- /// https://webrtc.github.io/samples/src/content/devices/input-output/
- const audioInputSelect = document.querySelector('select#audioSource');
- const audioOutputSelect = document.querySelector('select#audioOutput');
- const videoSelect = document.querySelector('select#videoSource');
- const selectors = [audioInputSelect, audioOutputSelect, videoSelect];
- /// This disables the selectfield for output if no output devices are found, seen on firefox for example
- audioOutputSelect.disabled = !('sinkId' in HTMLMediaElement.prototype);
- /// This populates the all select fields for all possible devices
- function gotDevices(deviceInfos) {
- // Handles being called several times to update labels. Preserve values.
- const values = selectors.map(select => select.value);
- selectors.forEach(select => {
- while (select.firstChild) {
- select.removeChild(select.firstChild);
- }
- });
- for (let i = 0; i !== deviceInfos.length; ++i) {
- const deviceInfo = deviceInfos[i];
- const option = document.createElement('option');
- option.value = deviceInfo.deviceId;
- if (deviceInfo.kind === 'audioinput') {
- option.text = deviceInfo.label || `microphone ${audioInputSelect.length + 1}`;
- audioInputSelect.appendChild(option);
- } else if (deviceInfo.kind === 'audiooutput') {
- option.text = deviceInfo.label || `speaker ${audioOutputSelect.length + 1}`;
- audioOutputSelect.appendChild(option);
- } else if (deviceInfo.kind === 'videoinput') {
- option.text = deviceInfo.label || `camera ${videoSelect.length + 1}`;
- videoSelect.appendChild(option);
- } else {
- console.log('Some other kind of source/device: ', deviceInfo);
- }
- }
- selectors.forEach((select, selectorIndex) => {
- if (Array.prototype.slice.call(select.childNodes).some(n => n.value === values[selectorIndex])) {
- select.value = values[selectorIndex];
- //console.log(values[selectorIndex]);
- }
- });
- }
- navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);
- // Attach audio output device to video element using device/sink ID.
- function attachSinkId(element, sinkId) {
- if (typeof element.sinkId !== 'undefined') {
- element.setSinkId(sinkId)
- .then(() => {
- console.log(`Success, audio output device attached: ${sinkId}`);
- })
- .catch(error => {
- let errorMessage = error;
- if (error.name === 'SecurityError') {
- errorMessage = `You need to use HTTPS for selecting audio output device: ${error}`;
- }
- console.error(errorMessage);
- // Jump back to first output device in the list as it's the default.
- audioOutputSelect.selectedIndex = 0;
- });
- } else {
- console.warn('Browser does not support output device selection.');
- }
- }
- /// Changes audio output by attaching a new sink id
- function changeAudioDestination() {
- const audioDestination = audioOutputSelect.value;
- attachSinkId(remoteVideo, audioDestination);
- }
- /// General handle error, actually not very useful, can be probably removed
- function handleError(error) {
- console.log('navigator.MediaDevices.getUserMedia error: ', error.message, error.name);
- }
- // Useful: https://webrtc.org/getting-started/media-devices
- /// Changes the device
- function ChangeDevice() {
- if (localStream) {
- localStream.getTracks().forEach(track => {
- track.stop();
- });
- }
- var audioSource = audioInputSelect.value;
- var videoSource = videoSelect.value;
- console.log(videoSource);
- console.log(audioSource);
- const newConstraints = {
- audio: {deviceId: audioSource ? {exact: audioSource} : undefined},
- video: {deviceId: videoSource ? {exact: videoSource} : undefined}
- };
- navigator.mediaDevices.getUserMedia(newConstraints).then(gotStream).then(gotDevices).catch(handleError);
- }
- audioInputSelect.onchange = ChangeDevice;
- audioOutputSelect.onchange = changeAudioDestination;
- videoSelect.onchange = ChangeDevice;
- /// END SELECT DEVICES
- var isChannelReady = false;
- var isInitiator = false;
- var isStarted = false;
- var localStream;
- var pc;
- var remoteStream;
- var turnReady;
- var pcConfig = {
- 'iceServers': [
- {
- 'urls': 'stun:stun.example.com:3478'
- },
- {
- 'urls': 'turn:turn.example.com:3478',
- 'credential': 'example',
- 'username': 'example'
- }
- ]
- };
- // Set up audio and video regardless of what devices are present.
- var sdpConstraints = {
- offerToReceiveAudio: true,
- offerToReceiveVideo: true
- };
- /////////////////////////////////////////////
- /// Initial room name
- var room;
- if (window.location.href.indexOf("?room") > -1) {
- room = window.location.href.split("?room=")[1];
- } else {
- room = makeid(10);
- window.location.href = window.location.href + "?room=" + room;
- }
- var socket = io.connect();
- if (room !== '') {
- socket.emit('create or join', room);
- console.log('Attempted to create or join room', room);
- }
- /*socket.on('disconnect', function(reason) {
- console.log('Disconnected: ', reason);
- });*/
- socket.on('created', function(room) {
- console.log('Created room ' + room);
- isInitiator = true;
- });
- socket.on('full', function(room) {
- console.log('Room ' + room + ' is full');
- });
- socket.on('join', function (room){
- console.log('Another peer made a request to join room ' + room);
- console.log('This peer is the initiator of room ' + room + '!');
- isChannelReady = true;
- });
- socket.on('joined', function(room) {
- console.log('joined: ' + room);
- isChannelReady = true;
- });
- socket.on('log', function(array) {
- console.log.apply(console, array);
- });
- ////////////////////////////////////////////////
- function sendMessage(message) {
- console.log('Client sending message: ', message);
- socket.emit('message', message);
- }
- // This client receives a message
- // Note message can be an object or a string (got user media)
- socket.on('message', function(message) {
- console.log('Client received message:', message);
- console.log('Client received message isStarted:', isStarted);
- if (message[0] === 'got user media') {
- console.log('message was got user media');
- maybeStart();
- } else if (message[0].type === 'offer') {
- if (!isInitiator && !isStarted) {
- maybeStart();
- }
- pc.setRemoteDescription(new RTCSessionDescription(message[0]));
- doAnswer();
- } else if (message[0].type === 'answer' && isStarted) {
- pc.setRemoteDescription(new RTCSessionDescription(message[0]));
- } else if (message[0].type === 'candidate' && isStarted) {
- var candidate = new RTCIceCandidate({
- sdpMLineIndex: message[0].label,
- candidate: message[0].candidate
- });
- pc.addIceCandidate(candidate);
- } else if (message[0] === 'bye' && isStarted) {
- handleRemoteHangup();
- }
- });
- ////////////////////////////////////////////////////
- var localVideo = document.querySelector('#localVideo');
- var remoteVideo = document.querySelector('#remoteVideo');
- // I added this block
- navigator.mediaDevices.getUserMedia = navigator.mediaDevices.getUserMedia
- || navigator.mediaDevices.mozGetUserMedia || navigator.mediaDevices.webkitGetUserMedia;
- var constraints = {
- audio: true,
- video: true
- };
- navigator.mediaDevices.getUserMedia(constraints).then(gotStream).then(gotDevices).catch(handleError);
- function gotStream(stream) {
- console.log('Adding local stream.');
- localStream = stream;
- localVideo.srcObject = stream;
- sendMessage(['got user media', room]);
- if (isInitiator) {
- maybeStart();
- }
- return navigator.mediaDevices.enumerateDevices(); // I added this
- }
- if (location.hostname !== 'localhost') {
- requestTurn(
- 'https://computeengineondemand.appspot.com/turn?username=41784574&key=4080218913'
- );
- }
- function maybeStart() {
- console.log('>>>>>>> maybeStart() ', isStarted, localStream, isChannelReady);
- if (!isStarted && typeof localStream !== 'undefined' && isChannelReady) {
- console.log('>>>>>> creating peer connection');
- createPeerConnection();
- pc.addStream(localStream);
- isStarted = true;
- console.log('isInitiator', isInitiator);
- if (isInitiator) {
- doCall();
- }
- }
- }
- // I removed this block
- //window.onbeforeunload = function() {
- // sendMessage(['bye', room]);
- //};
- /////////////////////////////////////////////////////////
- function createPeerConnection() {
- try {
- pc = new RTCPeerConnection(pcConfig); // I added pcConfig, was null
- pc.onicecandidate = handleIceCandidate;
- pc.onaddstream = handleRemoteStreamAdded;
- pc.onremovestream = handleRemoteStreamRemoved;
- console.log('Created RTCPeerConnnection');
- } catch (e) {
- console.log('Failed to create PeerConnection, exception: ' + e.message);
- alert('Cannot create RTCPeerConnection object.');
- return;
- }
- }
- function handleIceCandidate(event) {
- console.log('icecandidate event: ', event);
- if (event.candidate) {
- sendMessage([{
- type: 'candidate',
- label: event.candidate.sdpMLineIndex,
- id: event.candidate.sdpMid,
- candidate: event.candidate.candidate
- }, room]);
- } else {
- console.log('End of candidates.');
- }
- }
- function handleCreateOfferError(event) {
- console.log('createOffer() error: ', event);
- }
- function doCall() {
- console.log('Sending offer to peer');
- pc.createOffer(setLocalAndSendMessage, handleCreateOfferError);
- }
- function doAnswer() {
- console.log('Sending answer to peer.');
- pc.createAnswer().then(
- setLocalAndSendMessage,
- onCreateSessionDescriptionError
- );
- }
- function setLocalAndSendMessage(sessionDescription) {
- pc.setLocalDescription(sessionDescription);
- console.log('setLocalAndSendMessage sending message', sessionDescription);
- sendMessage([sessionDescription, room]);
- }
- function onCreateSessionDescriptionError(error) {
- trace('Failed to create session description: ' + error.toString());
- }
- function requestTurn(turnURL) {
- var turnExists = false;
- for (var i in pcConfig.iceServers) {
- if (pcConfig.iceServers[i].urls.substr(0, 5) === 'turn:') {
- console.log('Using turn: ' + pcConfig.iceServers[i].urls);
- turnExists = true;
- turnReady = true;
- break;
- }
- }
- if (!turnExists) {
- console.log('Getting TURN server from ', turnURL);
- // No TURN server. Get one from computeengineondemand.appspot.com:
- var xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function() {
- if (xhr.readyState === 4 && xhr.status === 200) {
- var turnServer = JSON.parse(xhr.responseText);
- console.log('Got TURN server: ', turnServer);
- pcConfig.iceServers.push({
- 'urls': 'turn:' + turnServer.username + '@' + turnServer.turn,
- 'credential': turnServer.password
- });
- turnReady = true;
- }
- };
- xhr.open('GET', turnURL, true);
- xhr.send();
- }
- }
- function handleRemoteStreamAdded(event) {
- console.log('Remote stream added.');
- remoteStream = event.stream;
- remoteVideo.srcObject = event.stream; // I changed form remoteStream to event.stream
- }
- function handleRemoteStreamRemoved(event) {
- console.log('Remote stream removed. Event: ', event);
- }
- function hangup() {
- console.log('Hanging up.');
- stop();
- sendMessage(['bye', room]);
- }
- function handleRemoteHangup() {
- console.log('Session terminated.');
- stop();
- isInitiator = false;
- }
- function stop() {
- isStarted = false;
- //isChannelReady = false; // I added this
- pc.close();
- pc = null;
- }
- /******************
- * Make a random ID
- ******************/
- function makeid(length) {
- var result = '';
- var characters = '0123456789';
- var charactersLength = characters.length;
- for ( var i = 0; i < length; i++ ) {
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement