🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 使用 electron 屏幕或摄像头录制并保存到本地 ## 获取媒体源信息 1. 获取摄像头和麦克源信息 ~~~javascript navigator.mediaDevices.enumerateDevices() .then(devices => devices.filter(d => d.kind === 'videoinput')) .then(devices => console.log(devices) // devices 为摄像头数组); ~~~ 2. 获取当前屏幕和应用窗口源信息 ~~~javascript desktopCapturer.getSources({ types: ['window', 'screen'] }, (error, sources) => { if (error) throw error; console.log(sources); // sources 当前屏幕和应用窗口的数组 }); ~~~ ## 使用 MediaRecorder 进行视频录制 首先根据选择的录制源是窗口还是摄像头以不同的方式获取视频流。 1. 媒体源是摄像头 ~~~javascript 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 })); ~~~ 2. 媒体源是屏幕或窗口 ~~~javascript let sourceId = ''; // 所选择的屏幕或窗口 sourceId let stream = navigator.mediaDevices.getUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: sourceId, maxWidth: window.screen.width, maxHeight: window.screen.height, }, }, }); ~~~ 3. 因为无法通过直接设置 audio: true 来获取音频,所以需要另外加入麦克风的音轨 ~~~javascript 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 保存至文件 1. createRecorder() 函数初始化录制 ~~~javascript 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); }; }, ~~~ 2. stopRecorder() 函数结束录制并保存至本地 mp4 文件 ~~~javascript 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); } ~~~