基于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 视频通话的关键代码跟流程!

例图:

相关推荐
ACP广源盛1392462567321 小时前
GSV2201S(1201S)@ACP#支持嵌入式 MCU 的 DisplayPort 1.4 到 HDMI 2.0 转换器
单片机·嵌入式硬件·电脑·音视频
前端达人1 天前
原生组件案例 04:5 个 div 打造「音频波形动效」
音视频
Android系统攻城狮1 天前
Android16音频之设置是否允许录音setAllowedCapturePolicy:用法实例(一百)
音视频·android16·音频进阶·是否允许录音
xixixi777772 天前
通信电子围栏——对特定终端(手机/物联网卡)进行实时监控和预警
安全·监控·通信·电子围栏·电子边界
好多渔鱼好多2 天前
【音视频】AI自适应均衡器的调节精度提升方法
人工智能·音视频
昨日之日20062 天前
InfiniteTalk V2版 - 声音驱动图片生成高度逼真的说话/唱歌视频 支持50系显卡 ComfyUI+WebUI 一键整合包下载
人工智能·深度学习·音视频
提娜米苏2 天前
唇语识别中的音频信号
音视频
汗流浃背了吧,老弟!2 天前
Langchian检索YouTube视频字幕
python·音视频
星野云联AIoT技术洞察2 天前
RTSP 与 WebRTC 对比:AI 物联网视频识别的最佳协议选择
webrtc·rtsp·实时传输·ai视频分析·iot视频流·iot集成·视频协议
TG:@yunlaoda360 云老大2 天前
AI 电影制作迈入新阶段:谷歌云Veo 3.1模型发布,实现音频全覆盖与精细化创意剪辑
人工智能·云计算·音视频·googlecloud