基于WebRTC实现音视频通话

客户端采用 WebRTC 技术(推流),通讯用 websocket。

WebRTC 像是一个面试过程:

第一步:发起方(拨打电话者)点击拨打电话时,获取本地媒体流并推流给接收方同时捕获接收方推过来的流,捕获到后把流设置到 dom 上,监听 ICE 候选确保能点对连接,生成 offer,通过 websocket 告知接收方并拉起等待接听界面。

复制代码
//获取媒体流
stream.value = await navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true
});

// 初始化 PeerConnection
peerConnection.value = new RTCPeerConnection({
    iceServers: [
        {
            urls: 'stun:stun.l.google.com:19302'
        }
    ]
});

// 推流给接收方
stream.value.getTracks().forEach((track) => {
    peerConnection.value.addTrack(track, stream.value);
});

// 捕获接收方的流
peerConnection.value.ontrack = (event) => {
    remoteStream.value = event.streams[0];
    if (callType.value === TypeVideo) {
        remoteVideo.value.srcObject = remoteStream.value;
    } else {
        remoteAudio.value.srcObject = remoteStream.value;
    }
};

// 监听ICE候选,确保 WebRTC 的点对点连接能够成功建立
peerConnection.value.onicecandidate = (event) => {
    if (event.candidate) {
        //发送candidate
        ws.send(event.candidate);
    }
};
// 创建 offer
const offer = await peerConnection.value.createOffer();
await peerConnection.value.setLocalDescription(offer);

//发送offer,这里发送的offer可以理解成是接收方用来捕获发起方流的一个凭证,接收方通过peerConnection.value.ontrack可以捕获到。
ws.send(offer);
//拉起等待接听界面
showCall.value = true;
//状态等待接听
callStatus.value = 'wating';

第二步:接收方收到 offer 后,第一步是拉起来电界面,第二步是选择接听或者挂断。

1)拉起来电接听界面

复制代码
//拉起来电接听界面
showCall.vue = true;
//状态来电接听
callStatus.value = 'coming';
//初始化来电人信息等
....

2)挂断,就是告诉发起方我挂断了,发起方就把 RTC 关掉、停止推流,dom 置空就好了

复制代码
//接收方
showCall.value = false;
callStatus.value = 'closing';
ws.send('reject');

//发起方
if (peerConnection.value) {
    peerConnection.value.close();
    peerConnection.value = null;
}
if (stream.value) {
    const tracks = stream.value.getTracks();
    tracks.forEach((track) => track.stop());
}
if (localVideo.value)
    localVideo.value.srcObject = null;
if (remoteVideo.value)
    remoteVideo.value.srcObject = null;
if (remoteAudio.value)
    remoteAudio.value.srcObject = null;
showCall.value = false;
callStatus.value = 'closing';

3)接听,操作跟拨打流程差不多,需要设置远端 SDP(发起方的 offer),添加 ICE 候选(发起方的 ice,这里需要注意的是只有远端 SDP 初始化完毕状态下才能设置 ice)

复制代码
// 获取本地媒体流
...同发起方
// 初始化 PeerConnection
...同发起方
// 推流给发起方
...同发起方
// 捕获发起方的流
...同发起方
// 监听ICE候选
...同发起方

//设置远端SDP
await peerConnection.value.setRemoteDescription(new RTCSessionDescription(caller.value.offer));

// 添加发起方发过来的ice
iceCandidateQueue.value.forEach(async (candidate) => {
await  peerConnection.value.addIceCandidate(candidate);
});
iceCandidateQueue.value  = [];

// 创建 answer
const  answer  =  await  peerConnection.value.createAnswer();
await  peerConnection.value.setLocalDescription(answer);

//发送answer给发起方
ws.send(answer);
//状态通话中
callStatus.value = 'calling';

关于 ice 的处理,就是远端 SDP 初始化完毕状态可以直接设置,未初始化完毕就存到 iceCandidateQueue 队列备用

复制代码
// 处理新的 ICE 候选
const handleNewICECandidate = async (candidate) => {
    const iceCandidate = new RTCIceCandidate(candidate);
    if (peerConnection.value?.signalingState === 'have-remote-offer' || peerConnection.value?.signalingState === 'stable') {
        peerConnection.value.addIceCandidate(iceCandidate);
    } else {
        iceCandidateQueue.value.push(iceCandidate);
    }
};

最后一步:发起方收到接收方的答复(接收方接听了),设置远端 SDP(接收方的 answer), 设置 ICE(接受方的 ice)

复制代码
//设置远端SDP
await peerConnection.value.setRemoteDescription(new RTCSessionDescription(caller.value.answer));

//添加ICE
iceCandidateQueue.value.forEach(async (candidate) => {
    await peerConnection.value.addIceCandidate(candidate);
});
iceCandidateQueue.value = [];
//状态接听中
callStatus.value = 'calling';

这就是 WebRTC 视频通话的关键代码跟流程!

例图:

相关推荐
s1533544 分钟前
RV1126 + FFPEG多路码流项目
音视频
智联视频超融合平台4 小时前
无人机+AI视频联网:精准狙击,让‘罪恶之花’无处藏身
人工智能·网络协议·安全·系统安全·音视频·无人机
周杰伦的稻香7 小时前
WordPress通过简码插入bilibili视频
音视频
Maxwellhang12 小时前
【音频处理】java流式调用ffmpeg命令
java·ffmpeg·音视频
liulilittle15 小时前
关于DDOS
linux·运维·服务器·网络·ddos·通信
_可乐无糖19 小时前
AWS WebRTC:获取ICE服务地址(part 3):STUN服务和TURN服务的作用
云计算·webrtc·aws
binary思维1 天前
视频压制(Video Encoding/Compression)
音视频
GCSXP1 天前
AU6825集成音频DSP的2x32W数字型ClaSSD音频功率放大器(替代TAS5825)
音视频
远瞻。1 天前
【论文精读】2024 ECCV--MGLD-VSR现实世界视频超分辨率(RealWorld VSR)
人工智能·算法·stable diffusion·音视频·超分辨率重建
音视频牛哥1 天前
技术创新如何赋能音视频直播行业?
音视频·大牛直播sdk·程序员创富·gb28181·rtsp播放器·rtmp播放器·职场人生