目前实现了 本地摄像头可以打开视频,可以拍照。
使用WEBSOCKET发送出去了。也接收了。但是接收到的数据无法显示视频。
可能是发送的问题。也可能是解析的问题。但是发送和接收的数据我检查了确实都是相同的BLOB数据。
有写过原生的指点一下。不要引用三方。完全原生JS。
<script>
const videoMimeType = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';//
//const videoMimeType = 'video/webm; codecs="opus, vp8"';
let myConstraints = {
audio: true,
video: {
facingMode: "user" //前置
}
};
let myWebSocket = null;
//Remote
let remoteMediaSource;
let remoteSourceBuffer;
let myVideo = document.getElementById("myVideo");
let remoteVideo = document.getElementById("remoteVideo");
async function openVideo() {
try {
//本地VIDEO-本地正常
var curStream = await navigator.mediaDevices.getUserMedia(myConstraints);
myVideo.srcObject = curStream;
myVideo.onloadedmetadata = function(evt) {
myVideo.play();
};
remoteVideo.onloadedmetadata = function(evt) {
remoteVideo.play(); //
};
//远程VIDEO-一直没办法显示
remoteMediaSource = new MediaSource();
remoteVideo.src = URL.createObjectURL(remoteMediaSource);
remoteMediaSource.addEventListener('sourceopen', () => {
//URL.revokeObjectURL(remoteVideo.src);
remoteSourceBuffer = remoteMediaSource.addSourceBuffer(videoMimeType);
remoteSourceBuffer.addEventListener('updateend', () => {
remoteMediaSource.endOfStream();
remoteVideo.play();
});
});
//////////////
//录制发送
let myMRecord = new MediaRecorder(curStream);
myMRecord.ondataavailable = function(curBlob) {
var txtLocal = document.getElementById("txtLocal");
txtLocal.value = (curBlob.data.size); //blob流
//data流;size为流大小
if (myWebSocket == null) {
ConnectWebSocket();
} else {
if (curBlob.data && curBlob.data.size > 0) {
if (myWebSocket != null) {
//这里的发送也是使用了两个方法,都不行;
//var fr = new FileReader();
//fr.readAsDataURL(curBlob.data);
//fr.onload = function (e) {
// myWebSocket.send(fr.result);
//};
myWebSocket.send(curBlob.data);
}
}
}
};
myMRecord.start(1000);
} catch {
alert("打开摄像头失败.");
}
}
function ConnectWebSocket() {
if (myWebSocket != null) return;
var wsUrl = "wss://www.address.com/ws/test";//自乙的地址一定要是HTTPS
myWebSocket = new WebSocket(wsUrl); //这个定义必须在方法前
myWebSocket.binaryType = 'arraybuffer'; //获取字节数据
myWebSocket.onopen = function(evt) {
//ViewLog("连接成功");
};
myWebSocket.onmessage = function(evt) {
//这里接收到的数据不知道如何解析;始终没有显示
remoteSourceBuffer.appendBuffer(evt.data);
// var fr = new FileReader();
// fr.onload = function(e) {
// remoteSourceBuffer.appendBuffer(e.target.result);
// };
// // Convert blob to ArrayBuffer
// fr.readAsArrayBuffer(evt.data);
};
myWebSocket.onclose = function(evt) {
myWebSocket = null;
alert("连接断开");
};
myWebSocket.onerror = function(evt) {
var msg = evt.data;
alert("错误:" + msg);
}
}
</script>
做websocket开发,可以自己搭建,也可以试试第三方的websocket框架。我近期在使用的GoEasy这个框架,在应对我们项目这种突发性的高并发需求上,表现不错。有websocket使用需求的也可以去看看,地址:https://www.goeasy.io/