custom.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. console.dir(element)
  20. if (element.srcObject === evt.streams[0]) return;
  21. element.srcObject = evt.streams[0];
  22. element.play();
  23. };
  24. peerConnection.onicecandidate = evt => {
  25. if (evt.candidate) ws.send(JSON.stringify({ type: 'candidate', ice: evt.candidate }));
  26. };
  27. ws.onmessage = (evt) => {
  28. const message = JSON.parse(evt.data);
  29. console.dir(message)
  30. switch (message.type) {
  31. case 'offer': {
  32. peerConnection.setRemoteDescription(message).then(() => {
  33. return peerConnection.createAnswer()
  34. }).then(answer => {
  35. return peerConnection.setLocalDescription(answer)
  36. }).then(() => {
  37. ws.send(JSON.stringify(peerConnection.localDescription));
  38. });
  39. break;
  40. }
  41. case 'answer': {
  42. peerConnection.setRemoteDescription(message);
  43. break;
  44. }
  45. case 'candidate': {
  46. peerConnection.addIceCandidate(new RTCIceCandidate(message.ice));
  47. break;
  48. }
  49. }
  50. };