webRTC-切换摄像头

切换摄像头可以通过改变 getMediaStream 的约束条件来实现。

前置摄像头:

1
2
3
4
5
6
constraints = {
audio: true,
video: {
facingMode: "user"
}
}

后置摄像头:

1
2
3
4
5
6
7
8
constraints = {
audio: true,
video: {
facingMode: {
exact: "environment"
}
}
}

切换摄像头:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
async function switchCamera() {
localStream.getTracks().forEach(track => {
track.stop();
});

constraints.video.facingMode = constraints.video.facingMode === "user" ? {exact: "environment"} : "user";
localStream = await getMediaStream(constraints).catch(() => {console.error("获取视频流失败")});

localVideo.value.srcObject = localStream;
localVideo.value.play();

localStream.getTracks().forEach(track => {
pc.getSenders().forEach(sender => {
sender.replaceTrack(track);
});
});
}

切换摄像头时,先把本地视频流停掉,然后根据约束条件获取新的视频流。

获取到新的视频流之后,为了在保持视频不断的情况下将其传到远端,可以用 RTCRtpSender.replaceTrack() 方法。