通过 electron desktopCapturer 和 navigator 获取要进行录制的媒体源信息;
使用 MediaRecorder 对视频流进行录制;
将 MediaRecorder 保存到本地文件。
获取媒体源信息
获取摄像头和麦克源信息
navigator.mediaDevices.enumerateDevices() .then(devices => devices.filter(d => d.kind === \'videoinput\')) .then(devices => console.log(devices) // devices 为摄像头数组);
获取当前屏幕和应用窗口源信息
desktopCapturer.getSources({ types: [\'window\', \'screen\'] }, (error, sources) => { if (error) throw error; console.log(sources); // sources 当前屏幕和应用窗口的数组 }); 使用 MediaRecorder 进行视频录制首先根据选择的录制源是窗口还是摄像头以不同的方式获取视频流。
媒体源是摄像头
let deviceId = \'\'; // 所选择的摄像头 deviceId let stream = navigator.mediaDevices.enumerateDevices() .then(device => device.find(d => d.kind === \'videoinput\' && d.deviceId === deviceId)) .then(video => navigator.mediaDevices.getUserMedia({ video }));
媒体源是屏幕或窗口
let sourceId = \'\'; // 所选择的屏幕或窗口 sourceId let stream = navigator.mediaDevices.getUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: \'desktop\', chromeMediaSourceId: sourceId, maxWidth: window.screen.width, maxHeight: window.screen.height, }, }, });
因为无法通过直接设置 audio: true 来获取音频,所以需要另外加入麦克风的音轨
stream .then(Mediastream => { let audioTracks = await navigator.mediaDevices .getUserMedia({ audio: true, video: false }) .then(mediaStream => mediaStream.getAudioTracks()[0]); stream.addTrack(audioTracks); createRecorder(stream); // createRecorder() 函数实现见下文 }) .catch(err => console.error(\'startRecord error\', err)); 将 MediaRecorder 保存至文件
createRecorder() 函数初始化录制
let recorder = null; function createRecorder(stream) { recorder = new MediaRecorder(stream); recorder.start(); // 如果 start 没设置 timeslice,ondataavailable 在 stop 时会触发 recorder.ondataavailable = event => { let blob = new Blob([event.data], { type: \'video/mp4\', }); saveMedia(blob); }; recorder.onerror = err => { console.error(err); }; },
stopRecorder() 函数结束录制并保存至本地 mp4 文件
function stopRecord() { recorder.stop(); } function saveMedia() { let reader = new FileReader(); reader.onload = () => { let buffer = new Buffer(reader.result); fs.writeFile(\'test.mp4\', buffer, {}, (err, res) => { if (err) return console.error(err); }); }; reader.onerror = err => console.error(err); reader.readAsArrayBuffer(blob); }以上,就顺利完成了使用 electron 录制视频功能,若有疑问可以加 qq (997494167) 进行交流。
Referencehttps://www.electronjs.org/docs/api/desktop-capturer
https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder
https://github.com/hokein/electron-screen-recorder