前端录制video标签视频,并保存本地
大致原理:MediaRecorder()作为录制器,录制video标签的画面,记录在canvas上,创建a标签,使用download进行本地下载。
1.html
首先用canvas标签,用来记录画面,可以不用显示,只用来记录画面。video标签用来播放视频。
<canvas :id="canvas" style="display:none"></canvas>
<video id="video" src=""></video>
2.js
录制用的api是MediaRecorder(可以去看一下这个api的参数),也可以使用navigator.mediaDevices.getUserMedia(),但是,安全网址(localhost,127.0.0.1,https)才可以使用,但是如果线上是https的,调试的时候可以设置一下浏览器,就可以本地调试了,不然navigator.mediaDevices是undefind。
//录像
startRecord(){
//已经在录像的
//recordStatus 记录录像的状态
if(this.recordStatus){
this.stopScreen()
}else{
this.startScreen()
}
},
//开始录像
async startScreen(){
this.recordStatus = true
//获取canvas和video的标签
this.canvasElement = document.querySelector("#canvas");
this.videoElement = documen.querySelector("#video");
this.canvasContext = this.canvasElement.getContext("2d");
this.chunks = [];
this.frameId = null;
//创建MediaRecorder,设置媒体参数
const stream = this.canvasElement.captureStream(60);
// MediaRecorder API
this.recorder = new MediaRecorder(stream, {
mimeType: 'video/webm;codecs=vp8',
videoBitsPerSecond : 2500000 //默认是2500000,说是越高越清晰,但是感觉没什么用
});
//收集录制数据
this.recorder.ondataavailable = e => {
this.chunks.push(e.data);
};
this.startTime = new Date().getTime()//记录一下开始时间!!
this.recorder.start(10);
this.drawFrame()
this.timeDuration()
},
drawFrame() {
// 捕捉录像画面放到canvas上面
this.canvasContext.drawImage(this.videoElement, 0, 0, this.canvasElement.width, this.canvasElement.height);
// 传入一个动画函数,返回一个浏览器定义的id
//好处一堆,可以自己百度
this.frameId = requestAnimationFrame(this.drawFrame);
},
stopScreen(){
this.recorder.stop()
this.recordStatus = false
cancelAnimationFrame(this.frameId)
this.download()
this.recorder = null
clearInterval(this.timeRecord)
this.timeRecord = null
},
// 录像的时间记录
timeDuration(){
//SecondFormat是全局定义的一个时间转换器,自己写一个就是了!!
this.timeRecord = setInterval(()=>{
let second = (new Date().getTime() - this.startTime)
this.videoTime = this.SecondFormat(second)
},1000)
},
//下载
download(){
let blob = new Blob(this.chunks);
let url = window.URL.createObjectURL(blob);
let link = document.createElement("a");
link.href = url;
link.download = "名字.mp4";
link.style.display = "none";
document.body.appendChild(link);
link.click();
link.remove();
},
完事自己设置个样式就是这样子的
好了,到这就完了,还是很简单易懂的代码的!!!
注意:可能会有一个问题:下载的视频,如果使用的播放视频的插件没有配置webm的话,就没有进度条和时间,比如腾讯视频就自动有进度条,爱奇艺就没有。但是这个也是可以解决的!
https://blog.csdn.net/qq_36958916/article/details/108529705 如果需要,这个可以解决进度跳的问题!