基于 Electron 的屏幕录制工具
主要基于 Chrome 内核提供的屏幕录制流(Stream)、麦克风流(Stream),进行画面与音频轨道合并。
最终会生成录制好的 webm 格式的文件,可以使用浏览器来打开它进行播放。或者使用 ffmpeg 类似的工具进行视频格式转换,使用其他工具进行播放。
实现效果如图所示:
核心代码如下:
const jQuery = (window.jQuery = require('jquery'));
require('@popperjs/core');
require('bootstrap');
const Vue = require('vue/dist/vue');
const electron = require('electron');
const fs = require('fs');
new Vue({
el: '#vueapp',
data: {
recording: false,
},
methods: {
async btnStartRecordClicked(e) {
this._stream = await navigator.mediaDevices.getUserMedia({
video: false,
audio: true,
});
let screenStream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
minWidth: 3072,
maxWidth: 3072,
minHeight: 1920,
maxHeight: 1920,
},
},
});
screenStream
.getVideoTracks()
.forEach((value) => this._stream.addTrack(value));
this.$refs.preview.srcObject = screenStream;
this._recorder = new MediaRecorder(this._stream, {
mimeType: 'video/webm;codes=h264',
});
this._recorder.ondataavailable = async (e) => {
let path = electron.remote.dialog.showSaveDialogSync(
electron.remote.getCurrentWindow(),
{
title: '保存文件',
defaultPath: 'ScreenData.webm',
}
);
let dataArrayBuffer = await e.data.arrayBuffer();
fs.writeFileSync(path, Buffer.from(dataArrayBuffer));
// fs.writeFileSync(path, new Uint8Array(dataArrayBuffer));
};
this._recorder.start();
this.recording = true;
},
btnStopRecordClicked(e) {
this.recording = false;
this._recorder.stop();
},
},
});
源码下载: