用到的相关API
- revokeObjectURL()、URL.createObjectURL()
- avigator.mediaDevices.getDisplayMedia()
new MediaRecorder()
页面布局
- video和三个按钮(start,stop,download)
分别点击对应三个事件,startCapture(),stopCapture(),mydownload()
实现
保存录制生成的视频可以借助Blob转换成二进制,然后,作为a元素的href属性,配合download属性,实现下载。
代码如下
const video = document.getElementById('video');
const start = document.getElementById('start');
const stop = document.getElementById('stop');
const download = document.getElementById('download');
const displayMediaOptions = {
video: {
cursor: "never"
},
audio: true
}
start.addEventListener('click',function(evt){
startCapture();
},false)
stop.addEventListener('click',function(evt){
stopCapture();
},false)
download.addEventListener('click',function(evt){
mydownload();
},false)
let captureStream;
let recorder;
async function startCapture() {
log = "";
try {
captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
} catch (err) {
console.log('Error: ' + err);
return alert('capture is error or cancel!');
}
// 删除原来的blob
window.URL.revokeObjectURL(video.src);
video.srcObject = captureStream;
recorder = new MediaRecorder(captureStream);
recorder.start();
}
function stopCapture() {
let tracks = video.srcObject.getTracks();
tracks.forEach(track => {
track.stop();
});
recorder.stop();
recorder.addEventListener('dataavailable',(event)=>{
let videoUrl = URL.createObjectURL(event.data,{type:'video/mp4'});
video.srcObject = null;
video.src = videoUrl;
})
}
function mydownload(){
const name = new Date().toISOString().slice(0,19).replace('T',' ').replace(' ','_').replace(/:/g,'-');
const a = document.createElement('a');
a.href = video.src;
a.download = `${name}.mp4`;
document.body.appendChild(a);
a.click();
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。