现在有个项目,在同html中有两个video,一个video打开摄像头录制视频,另一个video实时显示录制的视频,利用MediaRecoder、MediaSouce,求大神指导,代码如下:
test.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>摄像头调用</title>
<style>
#test {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<video id="v"></video>
<video id="test"></video>
<button onclick="openCamera()">启用摄像头</button>
<script>
var video = document.querySelector('#v');
var testVideo = document.querySelector('#test');
var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
var sourceBuffer;
var mediaRecorder;
var mediaStream;
// 接收视频并展示
var mediaSource = new MediaSource();
testVideo.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', (event) => {
console.log('mediaSource打开:', event);
sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
sourceBuffer.addEventListener('updateend', (event) => {
console.log('sourceBuffer更新结束:', event);
mediaSource.endOfStream();
testVideo.play();
});
});
function openCamera() {
var constraints = { audio: true, video: { width: 100, height: 100 } };
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
mediaStream = stream;
console.log('mediaStream-', mediaStream);
video.srcObject = mediaStream;
video.onloadedmetadata = function (e) {
console.log('视频可以使用', e);
console.dir(video);
video.play();
};
mediaRecorder = new MediaRecorder(mediaStream);
mediaRecorder.ondataavailable = (event) => {
event.data.arrayBuffer()
.then(data => {
sourceBuffer.appendBuffer(data);
console.log('正确正确');
}
);
}
mediaRecorder.start(1000);
})
.catch(err => { console.log(err.name + ": " + err.message); });
}
</script>
</body>
</html>
然后打开摄像头之后就会报如下的错误: