demo.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* eslint-env browser */
  2. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  3. // SPDX-License-Identifier: MIT
  4. const log = msg => {
  5. document.getElementById('logs').innerHTML += msg + '<br>'
  6. }
  7. window.createSession = isPublisher => {
  8. const pc = new RTCPeerConnection({
  9. iceServers: [
  10. {
  11. urls: 'stun:stun.l.google.com:19302'
  12. }
  13. ]
  14. })
  15. pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
  16. pc.onicecandidate = event => {
  17. if (event.candidate === null) {
  18. document.getElementById('localSessionDescription').value = btoa(JSON.stringify(pc.localDescription))
  19. }
  20. }
  21. if (isPublisher) {
  22. navigator.mediaDevices.getUserMedia({ video: true, audio: false })
  23. .then(stream => {
  24. stream.getTracks().forEach(track => pc.addTrack(track, stream))
  25. document.getElementById('video1').srcObject = stream
  26. pc.createOffer()
  27. .then(d => pc.setLocalDescription(d))
  28. .catch(log)
  29. }).catch(log)
  30. } else {
  31. pc.addTransceiver('video')
  32. pc.createOffer()
  33. .then(d => pc.setLocalDescription(d))
  34. .catch(log)
  35. pc.ontrack = function (event) {
  36. const el = document.getElementById('video1')
  37. el.srcObject = event.streams[0]
  38. el.autoplay = true
  39. el.controls = true
  40. }
  41. }
  42. window.startSession = () => {
  43. const sd = document.getElementById('remoteSessionDescription').value
  44. if (sd === '') {
  45. return alert('Session Description must not be empty')
  46. }
  47. try {
  48. pc.setRemoteDescription(JSON.parse(atob(sd)))
  49. } catch (e) {
  50. alert(e)
  51. }
  52. }
  53. window.copySDP = () => {
  54. const browserSDP = document.getElementById('localSessionDescription')
  55. browserSDP.focus()
  56. browserSDP.select()
  57. try {
  58. const successful = document.execCommand('copy')
  59. const msg = successful ? 'successful' : 'unsuccessful'
  60. log('Copying SDP was ' + msg)
  61. } catch (err) {
  62. log('Unable to copy SDP ' + err)
  63. }
  64. }
  65. const btns = document.getElementsByClassName('createSessionButton')
  66. for (let i = 0; i < btns.length; i++) {
  67. btns[i].style = 'display: none'
  68. }
  69. document.getElementById('signalingContainer').style = 'display: block'
  70. }