发送端
<div>
<canvas id="canvas"></canvas>
<video id="srcvideo"></video>
</div>
<div id="xs"></div>
<button id="startBtn" onclick="setRecorder(format);">开始</button>
<button id="stopBtn" onclick="stop()">结束</button>
<script>
let stream
let recorder
ws = new WebSocket('ws://127.0.0.1:8081')
navigator.mediaDevices.getUserMedia({video: true}).then(s => stream = s)
format = 'video/webm;codecs=vp8'
function setRecorder(format) {
recorder = new MediaRecorder(stream, {
mimeType: format
});
recorder.ondataavailable = e => {
ws.send(e.data)
}
recorder.start(10);
}
function stop() {
recorder.stop();
}
</script>
接收端
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<video controls autoplay ></video>
<script>
var video = document.querySelector('video');
var sourceBuffer
var mediaSource = new MediaSource;
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen);
function sourceOpen (_) {
sourceBuffer = this.addSourceBuffer('video/webm;codecs=vp8');
sourceBuffer.addEventListener('updateend', function (_) {})//video.play();});
};
ws=new WebSocket('ws://127.0.0.1:8081')
ws.onopen= function () {}
ws.onmessage=function onMessage(event){
var reader = new FileReader();
reader.onloadend = function(e){ sourceBuffer.appendBuffer(reader.result);}
reader.readAsArrayBuffer(event.data);
}
</script>
</body>
</html>
服务端
const express = require('express');
const app = express();
app.use(express.static('client'));
const wsInstance = require('express-ws')(app);
app.ws('/', ws => {
ws.on('message', data => {
wsInstance.getWss().clients.forEach(server => {
if (server !== ws) {
server.send(data);
}
});
});
});
app.listen(8081);
标签:function,websocket,实现,app,H5,ws,new,video,recorder
From: https://www.cnblogs.com/guanchaoguo/p/18058116