iT邦幫忙

2021 iThome 鐵人賽

DAY 24
0
Modern Web

後疫情時代的 WebRTC 微學習系列 第 24

Day24 [實作] 一對一視訊通話(4): 加入通話及掛斷機制

  • 分享至 

  • xImage
  •  

結合前兩篇我們已經實現了 MVP(Minimum Viable Product;最小可行產品),完成了最簡單的一對一通話,後續我們會慢慢強化他的功能,今天我們會加上通話及掛斷機制,運作方法如下圖。

https://ithelp.ithome.com.tw/upload/images/20211008/20130062bzuaVjosqv.png

Server 訂閱掛斷電話

收到 leave 消息後向對方發送bye 對自己發送 leaved

// 離開房間
socket.on('leave', (room) => {
  socket.to(room).emit('bye')
  socket.emit('leaved')
})

Client 添加掛電話功能

  1. index.html 中增加掛電話按鈕

    <div>
      <button id="leaveBtn">Leave</button>
    </div>
    
  2. main.js 中增加 掛斷電話

    function hangup() {
      if (peerConn) {
        peerConn.close()
        peerConn = null
      }
    }
    
  3. main.js 中增加 byeleaved 兩個訂閱

    // 收到 leaved 把 socket 中斷連線
    socket.on('leaved', (room, id) => {
      console.log('收到 leaved')
      // 中斷 socket
      socket.disconnect()
    })
    
    socket.on('bye', (room, id) => {
      console.log('收到 bye')
      // 對方要掛掉電話
      hunghp()
    })
    
  4. main.js 中增加 按鈕綁定

    const leaveBtn = document.querySelector('button#leaveBtn')
    
    // 點擊後發送離開的訊息並掛斷電話
    leaveBtn.onclick = () => {
      if (socket) {
        socket.emit('leave', room)
      }
      hangup()
    }
    

Client 加入啟動通話的功能

  1. index.html 中增加啟動通話按鈕

    <div>
      <button id="startBtn">Start</button>
      <button id="leaveBtn">Leave</button>
    </div>
    
  2. socket.io 相關程式碼使用function 包起來

    function connectIO() {
      // socket
      socket = io('ws://0.0.0.0:8080')
    
      socket.on('ready', async (msg) => {
        console.log(msg)
    
        // 發送 offer
        console.log('發送 offer ')
        await sendSDP(true)
      })
    
      socket.on('ice_candidate', async (data) => {
        console.log('收到 ice_candidate')
    
        const candidate = new RTCIceCandidate({
          sdpMLineIndex: data.label,
          candidate: data.candidate,
        })
        await peerConn.addIceCandidate(candidate)
      })
    
      socket.on('offer', async (desc) => {
        console.log('收到 offer')
    
        // 設定對方的配置
        await peerConn.setRemoteDescription(desc)
    
        // 發送 answer
        await sendSDP(false)
      })
    
      socket.on('answer', async (desc) => {
        console.log('收到 answer')
    
        // 設定對方的配置
        await peerConn.setRemoteDescription(desc)
      })
    
      socket.on('leaved', () => {
        console.log('收到 leaved')
        socket.disconnect()
      })
    
      socket.on('bye', () => {
        console.log('收到 bye')
        hangup()
      })
    
      socket.emit('join', room)
    }
    
  3. 替換初始化方法

    const startBtn = document.querySelector('button#startBtn')
    
    ...
    
    // window.onload = init()
    startBtn.onclick = init
    
  4. 加上按鈕控制

    async function init() {
      await createStream()
      initPeerConnection()
      connectIO()
      startBtn.disabled = true
      leaveBtn.disabled = false
    }
    
    leaveBtn.onclick = () => {
      if (socket) {
        socket.emit('leave', room)
      }
      hangup()
      startBtn.disabled = false
      leaveBtn.disabled = true
    }
    

完整程式碼:

  1. index.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>1on1 webrtc</title>
      </head>
      <body>
        <div>
          <button id="startBtn">Start</button>
          <button id="leaveBtn">Leave</button>
        </div>
    
        <div>
          <video muted width="320" autoplay playsinline id="localVideo"></video>
          <video width="320" autoplay playsinline id="remoteVideo"></video>
        </div>
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
        <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
        <script src="./js/main.js"></script>
      </body>
    </html>
    
  2. main.js

    // video 標籤
    const localVideo = document.querySelector('video#localVideo')
    const remoteVideo = document.querySelector('video#remoteVideo')
    
    // button 標籤
    const startBtn = document.querySelector('button#startBtn')
    const leaveBtn = document.querySelector('button#leaveBtn')
    
    let localStream
    let peerConn
    let socket
    const room = 'room1'
    
    function connectIO() {
      // socket
      socket = io('ws://0.0.0.0:8080')
    
      socket.on('ready', async (msg) => {
        console.log(msg)
        // 發送 offer
        console.log('發送 offer ')
        await sendSDP(true)
      })
    
      socket.on('ice_candidate', async (data) => {
        console.log('收到 ice_candidate')
        const candidate = new RTCIceCandidate({
          sdpMLineIndex: data.label,
          candidate: data.candidate,
        })
        await peerConn.addIceCandidate(candidate)
      })
    
      socket.on('offer', async (desc) => {
        console.log('收到 offer')
        // 設定對方的配置
        await peerConn.setRemoteDescription(desc)
    
        // 發送 answer
        await sendSDP(false)
      })
    
      socket.on('answer', async (desc) => {
        console.log('收到 answer')
    
        // 設定對方的配置
        await peerConn.setRemoteDescription(desc)
      })
    
      socket.on('leaved', () => {
        console.log('收到 leaved')
        socket.disconnect()
        closeLocalMedia()
      })
    
      socket.on('bye', () => {
        console.log('收到 bye')
        hangup()
      })
    
      socket.emit('join', room)
    }
    
    /**
     * 取得本地串流
     */
    async function createStream() {
      try {
        // 取得影音的Stream
        const stream = await navigator.mediaDevices.getUserMedia({
          audio: true,
          video: true,
        })
    
        // 提升作用域
        localStream = stream
    
        // 導入<video>
        localVideo.srcObject = stream
      } catch (err) {
        throw err
      }
    }
    
    /**
     * 初始化Peer連結
     */
    function initPeerConnection() {
      const configuration = {
        iceServers: [
          {
            urls: 'stun:stun.l.google.com:19302',
          },
        ],
      }
      peerConn = new RTCPeerConnection(configuration)
    
      // 增加本地串流
      localStream.getTracks().forEach((track) => {
        peerConn.addTrack(track, localStream)
      })
    
      // 找尋到 ICE 候選位置後,送去 Server 與另一位配對
      peerConn.onicecandidate = (e) => {
        if (e.candidate) {
          console.log('發送 ICE')
          // 發送 ICE
          socket.emit('ice_candidate', room, {
            label: e.candidate.sdpMLineIndex,
            id: e.candidate.sdpMid,
            candidate: e.candidate.candidate,
          })
        }
      }
    
      // 監聽 ICE 連接狀態
      peerConn.oniceconnectionstatechange = (e) => {
        if (e.target.iceConnectionState === 'disconnected') {
          remoteVideo.srcObject = null
        }
      }
    
      // 監聽是否有流傳入,如果有的話就顯示影像
      peerConn.onaddstream = ({ stream }) => {
        // 接收流並顯示遠端視訊
        remoteVideo.srcObject = stream
      }
    }
    
    /**
     * 處理信令
     * @param {Boolean} isOffer 是 offer 還是 answer
     */
    async function sendSDP(isOffer) {
      try {
        if (!peerConn) {
          initPeerConnection()
        }
    
        // 創建SDP信令
        const localSDP = await peerConn[isOffer ? 'createOffer' : 'createAnswer']({
          offerToReceiveAudio: true, // 是否傳送聲音流給對方
          offerToReceiveVideo: true, // 是否傳送影像流給對方
        })
    
        // 設定本地SDP信令
        await peerConn.setLocalDescription(localSDP)
    
        // 寄出SDP信令
        let e = isOffer ? 'offer' : 'answer'
        socket.emit(e, room, peerConn.localDescription)
      } catch (err) {
        throw err
      }
    }
    
    /**
     * 關閉自己的視訊
     */
    function closeLocalMedia() {
      if (localStream && localStream.getTracks()) {
        localStream.getTracks().forEach((track) => {
          track.stop()
        })
      }
      localStream = null
    }
    
    /**
     * 掛掉電話
     */
    function hangup() {
      if (peerConn) {
        peerConn.close()
        peerConn = null
      }
    }
    
    /**
     * 初始化
     */
    async function init() {
      await createStream()
      initPeerConnection()
      connectIO()
      startBtn.disabled = true
      leaveBtn.disabled = false
    }
    
    // window.onload = init()
    
    leaveBtn.onclick = () => {
      if (socket) {
        socket.emit('leave', room)
      }
      hangup()
      startBtn.disabled = false
      leaveBtn.disabled = true
    }
    
    startBtn.onclick = init
    

上一篇
Day23 [實作] 一對一視訊通話(3): Client
下一篇
Day25 [實作] 一對一視訊通話(5): 切換設備
系列文
後疫情時代的 WebRTC 微學習30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言