demo.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. // Offer to receive 1 audio, and 1 video track
  26. pc.addTransceiver('video', {
  27. direction: 'sendrecv'
  28. })
  29. pc.addTransceiver('audio', {
  30. direction: 'sendrecv'
  31. })
  32. pc.createOffer().then(d => pc.setLocalDescription(d)).catch(log)
  33. window.startSession = () => {
  34. const sd = document.getElementById('remoteSessionDescription').value
  35. if (sd === '') {
  36. return alert('Session Description must not be empty')
  37. }
  38. try {
  39. pc.setRemoteDescription(JSON.parse(atob(sd)))
  40. } catch (e) {
  41. alert(e)
  42. }
  43. }
  44. window.copySessionDescription = () => {
  45. const browserSessionDescription = document.getElementById('localSessionDescription')
  46. browserSessionDescription.focus()
  47. browserSessionDescription.select()
  48. try {
  49. const successful = document.execCommand('copy')
  50. const msg = successful ? 'successful' : 'unsuccessful'
  51. log('Copying SessionDescription was ' + msg)
  52. } catch (err) {
  53. log('Oops, unable to copy SessionDescription ' + err)
  54. }
  55. }