示例代码
var buffer;
// 创建录制对象
var mediaRecorder;
// 当该函数被触发后,将数据压入到 blob 中
function handleDataAvailable(e){
if(e && e.data && e.data.size > 0){
buffer.push(e.data);
}
}
function startRecord(){
// 防止多次启动报错
if(mediaRecorder && mediaRecorder.state === "recording"){
return;
}
buffer = [];
// 设置录制下来的多媒体格式
var options = {
mimeType: 'video/webm;codecs=vp8'
}
// 判断浏览器是否支持录制
if(!MediaRecorder.isTypeSupported(options.mimeType)){
console.error(`${options.mimeType} is not supported!`);
return;
}
try{
mediaRecorder = new MediaRecorder(videoplay.srcObject, options);
}catch(e){
console.error('Failed to create MediaRecorder:', e);
return;
}
// 当有音视频数据来了之后触发该事件
mediaRecorder.ondataavailable = handleDataAvailable;
// 开始录制
mediaRecorder.start(10);
}
function startRecplay(){
console.log(mediaRecorder)
var blob = new Blob(buffer, {type: 'video/webm'});
recvideo.src = window.URL.createObjectURL(blob);
recvideo.srcObject = null;
recvideo.controls = true;
recvideo.play();
}
function download(){
var blob = new Blob(buffer, {type: 'video/webm'});
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.style.display = 'none';
a.download = 'aaa.webm';
a.click();
a.remove();
}
function stop(){
if(mediaRecorder && (mediaRecorder.state === "recording" || mediaRecorder.state === "paused")){
mediaRecorder.stop();
}
}
展开