通过MediaRecorder在Electron中录制时,视频输出为0字节

时间:2019-03-30 10:24:01

标签: javascript electron

我试图通过ScreenCapturer在Electron中记录当前屏幕,但是当我尝试将其保存在磁盘上时,我得到了一个0字节大小的文件。我也在我的应用程序控制台上收到此错误:

(node:13704) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

在网络版本中,我只需使用window.URL.createObjectURL(blob)就可以了!但在电子中,我想我需要带缓冲的东西?有人可以向我解释为什么会这样吗?谢谢!

const {desktopCapturer} = require('electron');
const fs = require('graceful-fs');

const SECRET_KEY = 'Electron 69';
let recorder;
let blobs = [];

const startRecording = () => {
    let title = document.title;
    document.title = SECRET_KEY;

    desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
        if (error) throw error;
        for (let source of sources) {
            if (source.name === SECRET_KEY) {
                document.title = title;

                navigator.mediaDevices.getUserMedia({
                    audio: false,
                    video: {
                        mandatory: {
                            chromeMediaSource: 'desktop',
                            chromeMediaSourceId: source.id,
                            minWidth: 1280,
                            maxWidth: 1280,
                            minHeight: 720,
                            maxHeight: 720
                        }
                    }
                }).then((stream) => handleStream(stream))
                    .catch((e) => handleError(e));
                return
            }
        }
    });
};

function handleStream(stream) {
    recorder = new MediaRecorder(stream);
    blobs = [];
    recorder.ondataavailable = function(event) {
        blobs.push(event.data);
    };
    recorder.start();
}

function stopRecording() {
    recorder.stop();
    toArrayBuffer(new Blob(blobs, {type: 'video/mp4'}), function(ab) {
        const buffer = toBuffer(ab);
        const file = `./record.mp4`;
        fs.writeFile(file, buffer, function(err) {
            if (err) {
                console.error('Failed to save video ' + err);
            } else {
                console.log('Saved video: ' + file);
            }
        });
    });
}

function handleError(e) {
    console.error('handleUserMediaError', e);
}

function toArrayBuffer(blob, cb) {
    let fileReader = new FileReader();
    fileReader.onload = function() {
        let arrayBuffer = this.result;
        cb(arrayBuffer);
    };
    fileReader.readAsArrayBuffer(blob);
}

function toBuffer(ab) {
    let buffer = new Buffer(ab.byteLength);
    let arr = new Uint8Array(ab);
    for (let i = 0; i < arr.byteLength; i++) {
        buffer[i] = arr[i];
    }
    return buffer;
}

// Record for 3 seconds and save to disk
startRecording();
setTimeout(function() { stopRecording() }, 3000);

0 个答案:

没有答案