demo.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* eslint-env browser */
  2. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  3. // SPDX-License-Identifier: MIT
  4. const pc = new RTCPeerConnection({
  5. iceServers: [
  6. {
  7. urls: 'stun:stun.l.google.com:19302'
  8. }
  9. ]
  10. })
  11. const log = msg => {
  12. document.getElementById('logs').innerHTML += msg + '<br>'
  13. }
  14. navigator.mediaDevices.getUserMedia({ video: true, audio: true })
  15. .then(stream => {
  16. stream.getTracks().forEach(track => pc.addTrack(track, stream))
  17. document.getElementById('video1').srcObject = stream
  18. pc.createOffer().then(d => pc.setLocalDescription(d)).catch(log)
  19. }).catch(log)
  20. pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
  21. pc.onicecandidate = event => {
  22. if (event.candidate === null) {
  23. document.getElementById('localSessionDescription').value = btoa(JSON.stringify(pc.localDescription))
  24. }
  25. }
  26. window.startSession = () => {
  27. const sd = document.getElementById('remoteSessionDescription').value
  28. if (sd === '') {
  29. return alert('Session Description must not be empty')
  30. }
  31. try {
  32. pc.setRemoteDescription(JSON.parse(atob(sd)))
  33. } catch (e) {
  34. alert(e)
  35. }
  36. }
  37. window.copySDP = () => {
  38. const browserSDP = document.getElementById('localSessionDescription')
  39. browserSDP.focus()
  40. browserSDP.select()
  41. try {
  42. const successful = document.execCommand('copy')
  43. const msg = successful ? 'successful' : 'unsuccessful'
  44. log('Copying SDP was ' + msg)
  45. } catch (err) {
  46. log('Unable to copy SDP ' + err)
  47. }
  48. }