简单demo
var deskVideo = document.querySelector("video#deskVideo");
function getDeskStream(stream){
deskVideo.srcObject = stream;
}
// 对采集的数据做一些限制
var constraints = {
video : {
width: 1280,
height: 720,
frameRate:15,
},
audio : false
}
function handleError(err){
console.log('getUserMedia error:', err);
}
function IsPC() {
var userAgentInfo = navigator.userAgent;
var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPod", "iPad"];
var flag = true;
for (var i = 0; i < Agents.length; i++) {
if (userAgentInfo.indexOf(Agents[i]) > 0) {
flag = false;
break;
}
}
return flag;
};
// 抓取桌面
function shareDesktop(){
// 只有在 PC 下才能抓取桌面
if(IsPC()){
// 开始捕获桌面数据
navigator.mediaDevices.getDisplayMedia(constraints)
.then(getDeskStream)
.catch(handleError);
return true;
}
return false;
}
var buffer;
// 创建录制对象
var mediaRecorder;
function handleDataAvailable(e){
if(e && e.data && e.data.size > 0){
buffer.push(e.data);
}
}
function startRecord(){
// 定义一个数组,用于缓存桌面数据,最终将数据存储到文件中
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(deskVideo.srcObject, options);
}catch(e){
console.error('Failed to create MediaRecorder:', e);
return;
}
// 当捕获到桌面数据后,该事件触发
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start(10);
}
document.querySelector("button#record").onclick = function (){
startRecord();
}
shareDesktop()
展开