demo.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. urls: 'stun:stun.l.google.com:19302'
  7. }]
  8. })
  9. const log = msg => {
  10. document.getElementById('div').innerHTML += msg + '<br>'
  11. }
  12. pc.ontrack = function (event) {
  13. const el = document.createElement(event.track.kind)
  14. el.srcObject = event.streams[0]
  15. el.autoplay = true
  16. el.controls = true
  17. document.getElementById('remoteVideos').appendChild(el)
  18. }
  19. pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
  20. pc.onicecandidate = event => {
  21. if (event.candidate === null) {
  22. document.getElementById('localSessionDescription').value = btoa(JSON.stringify(pc.localDescription))
  23. }
  24. }
  25. navigator.mediaDevices.getUserMedia({ video: true, audio: true })
  26. .then(stream => {
  27. document.getElementById('video1').srcObject = stream
  28. stream.getTracks().forEach(track => pc.addTrack(track, stream))
  29. pc.createOffer().then(d => pc.setLocalDescription(d)).catch(log)
  30. }).catch(log)
  31. window.startSession = () => {
  32. const sd = document.getElementById('remoteSessionDescription').value
  33. if (sd === '') {
  34. return alert('Session Description must not be empty')
  35. }
  36. try {
  37. pc.setRemoteDescription(JSON.parse(atob(sd)))
  38. } catch (e) {
  39. alert(e)
  40. }
  41. }
  42. window.copySessionDescription = () => {
  43. const browserSessionDescription = document.getElementById('localSessionDescription')
  44. browserSessionDescription.focus()
  45. browserSessionDescription.select()
  46. try {
  47. const successful = document.execCommand('copy')
  48. const msg = successful ? 'successful' : 'unsuccessful'
  49. log('Copying SessionDescription was ' + msg)
  50. } catch (err) {
  51. log('Oops, unable to copy SessionDescription ' + err)
  52. }
  53. }