前言
一直想借助webRTC实现一个一对一视频, 但是网上找了很多教程, 要么只实现到获取本地视频流, 要么就是随便搪塞两句, 很少有能够完整实现一个一对一音视频的demo,因此便自己摸索,实现了一个Demo,希望能够加深自己的webRTC的理解
流程图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| sequenceDiagram participant ClientA participant Server participant ClientB ClientA->>Server: 连接信令服务器(ws/http) ClientA->>ClientA: rtc = new RTCPeerConnection(config) ClientA->>ClientA: 添加rtc, 信令服务器信令监听 ClientB->>Server: 连接信令服务器(ws/http) ClientB->>ClientB: rtc = new RTCPeerConnection(config) ClientB->>ClientB: 添加rtc, 信令服务器信令监听 ClientA->>ClientA: 获取本地流(getUserMedia) ClientA-->>ClientA: 设置本地预览 ClientA->>ClientA: rtc.addTrack ClientB->>ClientB: 获取本地流(getUserMedia) ClientB-->>ClientB: 设置本地预览 ClientB->>ClientB: rtc.addTrack Note left of ClientA: 用户触发call指令 ClientA->>Server: 发送call信令(ws/http) Server->>ClientA: 你是发起人 ClientA->>ClientA: offer = await rtc.createOffer() ClientA->>ClientA: rtc.setLocalDescription(offer) Server->>ClientB: 你是接收人 ClientB->>ClientB: answer = await rtc.createAnswer() ClientB->>ClientB: rtc.setLocalDescription(answer) ClientA->>Server: 发送sdp: offer ClientB->>Server: 发送sdp: answer Server->>ClientB: 发送sdp(from ClientA) Server->>ClientA: 发送sdp(from ClientB) ClientA->>ClientA: rtc.setRemoteDescription(sdp) ClientB->>ClientB: rtc.setRemoteDescription(sdp) Note left of ClientA: rtc.on('icecandidate') ClientA->>Server: 发送icecandidate Server->>ClientB: 发送ClientA的icecandidate ClientB->>ClientB: rtc.addIceCandidate(icecandidate) Note right of ClientB: rtc.on('icecandidate') ClientB->>Server: 发送icecandidate Server->>ClientA: 发送ClientA的icecandidate ClientA->>ClientA: rtc.addIceCandidate(icecandidate) Note left of ClientA: rtc.on('track') ClientA->>ClientA: 播放远端流 Note right of ClientB: rtc.on('track') ClientB->>ClientB: 播放远端流
|
ps: ClientA和ClientB是对等端, 谁发起都可以, 这里服务器要做jungle,确定谁创建offer,谁创建answer
实现
其实上面的流程图已经基本写到了所有一对一音视频中的所有点,自己写了一个很初级的demo
webrtc-demo
chat-server