页面上俩个窗口
<video id="localVideo" style="width: 320px; height: 240px;" autoplay muted></video>
<video id="remoteVideo" style="width: 320px; height: 240px;" autoplay muted></video>
此处是在一进来就在mounted建立了,可自行根据代码逻辑调整位置
ws = new WebSocket("ws://192.168.0.xxx:9000");
// 推流用的MediaStream
pc = new RTCPeerConnection();
let that = this;
//此处监听 而后发送信息
pc.addEventListener("icecandidate", event => {
if (event.candidate) {
ws.send(
JSON.stringify({
type: iceType,
candidate: event.candidate
})
);
}
});
pc.addEventListener("track", event => {
that.remoteVideo.srcObject = event.streams[0];
});
打开摄像头(手动调用)
async hanldeJoin() {
this.show = false;
if (!this.roomId) {
this.$message.warning("请输入房间号");
return;
}
this.caller = true;
this.calling = true;
let that = this;
this.$nextTick(() => {
that.localVideo = document.getElementById("localVideo");
that.remoteVideo = document.getElementById("remoteVideo");
});
try {
stream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: true
});
//创建媒体录制对象
// that.recorder = new window.MediaRecorder(stream);
// that.bindEvents();
that.localVideo.srcObject = stream;
that.localVideo.play();
that.localStream = stream;
// 房间号参数自行调整 1v1未带入,连入同一个websocket即可
that.doJoin(that.roomId);
} catch (err) {
that.$message.warning("无法访问用户媒体设备");
console.error(err); // 无法访问用户媒体设备
alert(err);
}
},
async doJoin(roomId) {
ws.send(
JSON.stringify({
type: "connect"
})
);
// 收到服务端消息
ws.onmessage = function(evt) {
if (typeof evt.data == "string") {
var str = evt.data;
if (str.length <= 0) {
return;
} else {
//处理其他请求
let event = JSON.parse(str);
switch (event.type) {
case "connect":
console.log("连接成功,等待其他用户");
break;
case "create_offer":
that.sendOffer();
break;
case "offer":
that.caller = false;
that.recvOffer(event);
break;
case "answer":
that.caller = false;
that.recvAnswer(event);
break;
case "offer_ice":
case "answer_ice":
pc.addIceCandidate(event.sdp);
break;
default:
break;
}
}
}
};
},
rtc的传递
sendOffer() {
iceType = "offer_ice";
pc.addTrack(this.localStream.getVideoTracks()[0], this.localStream);
pc.createOffer({
offerToReceiveAudio: true,
offerToReceiveVideo: true
}).then(offer => {
pc.setLocalDescription(offer).then(() => {
ws.send(JSON.stringify(offer));
});
});
},
recvOffer(offer) {
iceType = "answer_ice";
pc.addTrack(this.localStream.getVideoTracks()[0], this.localStream);
pc.setRemoteDescription(offer).then(() => {
pc.createAnswer().then(answer => {
pc.setLocalDescription(answer).then(() => {
ws.send(JSON.stringify(answer));
});
});
});
},
recvAnswer(answer) {
pc.setRemoteDescription(answer);
},