Cesium 使用MediaStreamRecorder 或者MediaRecorder录屏并下载视频,以及开启摄像头录像。【转】
Cesium录制canvas视频
利用H5 API MediaRecorder 并借用canvas.captureStream录制屏幕。
安装MediaRecorder
npm install msr
直接上代码(vue下)
recorderCanvas () { let that = this let viewer = window.earth const stream = viewer.canvas.captureStream() const recorder = new MediaRecorder(stream, { MimeType: 'video/webm' }) that.data = [] recorder.ondataavailable = function (event) { if (event.data && event.data.size) { that.data.push(event.data) } } recorder.onstop = () => { that.url = URL.createObjectURL(new Blob(that.data, { type: 'video/webm' })) that.startDownload(that.url) // 这里创建a标签下载就好了 } recorder.start() setTimeout(() => { recorder.stop() }, 10000) },
缺点:只能录制canvas, 页面其他dom录制不了。
附加个打开摄像头录像的,同样采用MediaRecorder 或者 MediaStreamRecorder ,MediaStreamRecorder 提供了更多控制手段,需要把相应的js文件引入。
MediaStreamRecorder GitHub地址
MediaRecorder 方式
注意点,建立MediaRecorder实例时,要正确设置mimeType的值,否则,下载下来的视频会是黑屏,另外视频格式chrome好像只支持wemp格式。
调用MediaRecorder.stop()并不会关闭摄像头,需要手动stream.getTracks关闭视频和音频。
makeRecordes () { if (navigator.mediaDevices) { console.log('getUserMedia supported.') var constraints = { audio: true, video: { width: 1280, height: 720 } } var chunks = [] let that = this navigator.mediaDevices.getUserMedia(constraints) .then(function (stream) { var mediaRecorder = new MediaRecorder(stream, { mimeType: 'video/webm;codecs=vp8,opus' }) mediaRecorder.start() mediaRecorder.ondataavailable = function (e) { chunks.push(e.data) } setTimeout(() => { mediaRecorder.stop() // 关闭摄像头 stream.getTracks().forEach(function (track) { track.stop() }) mediaRecorder.onstop = () => { const videoBlob = new Blob(chunks, { 'type': 'video/webm' }) let videoUrl = window.URL.createObjectURL(videoBlob) that.startDownload(videoUrl) } }, 10000) }) .catch(function (err) { console.log('The following error occurred: ' + err) }) } },
如果你需要更多的控制,比如暂停,又不想自己实现,那就用MediaStreamRecorder
同样要正确设置值mimeType,否则录得视频会黑屏。
makeRecordesByMSR () { if (navigator.mediaDevices) { console.log('getUserMedia supported.') var constraints = { audio: true, video: { width: 1280, height: 720 } } navigator.mediaDevices.getUserMedia(constraints) .then(function (stream) { // eslint-disable-next-line no-undef var mediaRecorder = new MediaStreamRecorder(stream) mediaRecorder.stream = stream mediaRecorder.width = window.screen.width mediaRecorder.height = window.screen.height mediaRecorder.mimeType = 'video/webm;codecs=vp8,opus' mediaRecorder.ondataavailable = function (blob) { mediaRecorder.save(blob, 'myName.webm') } mediaRecorder.start(6000) setTimeout(() => { mediaRecorder.stream.stop() }, 12000) }) .catch(function (err) { console.log('The following error occurred: ' + err) }) } }
原文链接:https://blog.csdn.net/qq_42081843/article/details/119005254
饮水思源,不忘初心。
要面包,也要有诗和远方。