demo.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. pc.createOffer().then(d => pc.setLocalDescription(d)).catch(log)
  18. }).catch(log)
  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. pc.ontrack = function (event) {
  26. const el = document.createElement(event.track.kind)
  27. el.srcObject = event.streams[0]
  28. el.autoplay = true
  29. el.controls = true
  30. document.getElementById('remoteVideos').appendChild(el)
  31. }
  32. window.startSession = () => {
  33. const sd = document.getElementById('remoteSessionDescription').value
  34. if (sd === '') {
  35. return alert('Session Description must not be empty')
  36. }
  37. try {
  38. pc.setRemoteDescription(JSON.parse(atob(sd)))
  39. } catch (e) {
  40. alert(e)
  41. }
  42. }
  43. window.copySDP = () => {
  44. const browserSDP = document.getElementById('localSessionDescription')
  45. browserSDP.focus()
  46. browserSDP.select()
  47. try {
  48. const successful = document.execCommand('copy')
  49. const msg = successful ? 'successful' : 'unsuccessful'
  50. log('Copying SDP was ' + msg)
  51. } catch (err) {
  52. log('Unable to copy SDP ' + err)
  53. }
  54. }