custom.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. let peerConnection = new RTCPeerConnection({ "iceServers": [{ "urls": "stun:stun.l.google.com:19302" }] }),
  2. ws = new WebSocket((window.location.protocol === "https:" ? "wss://" : "ws://") + window.location.host + '/video/connections' + window.location.search);
  3. navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(stream => {
  4. let element = document.getElementById('local_video');
  5. element.srcObject = stream;
  6. element.play().then(() => {
  7. stream.getTracks().forEach(track => peerConnection.addTrack(track, stream));
  8. peerConnection.onnegotiationneeded = () => {
  9. peerConnection.createOffer().then(offer => {
  10. return peerConnection.setLocalDescription(offer);
  11. }).then(() => {
  12. ws.send(JSON.stringify(peerConnection.localDescription));
  13. });
  14. }
  15. });
  16. });
  17. peerConnection.ontrack = evt => {
  18. let element = document.getElementById('remote_video');
  19. if (element.srcObject === evt.streams[0]) return;
  20. element.srcObject = evt.streams[0];
  21. element.play();
  22. };
  23. peerConnection.onicecandidate = evt => {
  24. if (evt.candidate) ws.send(JSON.stringify({ type: 'candidate', ice: evt.candidate }));
  25. };
  26. ws.onmessage = (evt) => {
  27. const message = JSON.parse(evt.data);
  28. switch (message.type) {
  29. case 'offer': {
  30. peerConnection.setRemoteDescription(message).then(() => {
  31. return peerConnection.createAnswer()
  32. }).then(answer => {
  33. return peerConnection.setLocalDescription(answer)
  34. }).then(() => {
  35. ws.send(JSON.stringify(peerConnection.localDescription));
  36. });
  37. break;
  38. }
  39. case 'answer': {
  40. peerConnection.setRemoteDescription(message);
  41. break;
  42. }
  43. case 'candidate': {
  44. peerConnection.addIceCandidate(new RTCIceCandidate(message.ice));
  45. break;
  46. }
  47. }
  48. };