Save video blob to filesystem electron/node js
Asked Answered
B

3

12

In my electron application, users can record video from their webcam using the MediaRecorder API.

When the user hit the "stop record" button, I get a blob of the recorded video.

What i would like to do is to convert this blob to a real webm video and write it into the user's filesystem with for example :

fs.writeFile(localdir + '\\video.webm', videoBlob); // does not work

The example below works pretty well with base64 image snapshot that I get from the webcam, but i can't make it work with the video blob that I get.

Thanks for enlighten me !

Bathsheb answered 19/10, 2016 at 17:26 Comment(0)
H
23

An alternative to FileReader is a promise-based approach via Blob's arrayBuffer method:

async function saveFile() {

    const blob = new Blob(chunks, {
        type: 'video/webm'
    })


    const buffer = Buffer.from( await blob.arrayBuffer() );

    fs.writeFile('video.webm', buffer, () => console.log('video saved!') );

}
Hardden answered 29/2, 2020 at 19:27 Comment(2)
How can one do this with puppeteer's expose function ? Seems like sending blob or array buffer to the exposed function doesn't work because argument is JSON.strigified. blob.text() works to send it to the expose function but I'm not sure how to save it as a video file later. All my efforts end up with a corrupted video file :/Emu
Saved by Jeff himself!Conjunct
K
6

Create a video blob. chunks is an array of event.data from a MediaRecorder instance's ondataavailable

var blob = new Blob(chunks, {
    type: 'video/webm'
})

Read the blob as an ArrayBuffer, and use that to create a Buffer. Save the buffer as a file.

var reader = new FileReader()
reader.onload = function(){
    var buffer = new Buffer(reader.result)
    fs.writeFile(path, buffer, {}, (err, res) => {
        if(err){
            console.error(err)
            return
        }
        console.log('video saved')
    })
}
reader.readAsArrayBuffer(blob)
Kidney answered 31/12, 2016 at 18:44 Comment(2)
I also have to contribute with a downvote here, because while this is indeed the obvious solution, it forces the Blob data to be read into memory, which may not exactly be gentle when you have a few hours of video (the Blob may or may not reside in memory by itself depending on how the browser decides, and if it doesn't, doing this will nuke it into the RAM).Asclepiadean
@JohnWeisz IMO that's an edge case. I'd be happy to see your solution for that, regardlessKidney
O
0

You need to use FileReader to read blob contents as an array and then create a Buffer instance.

I cannot get the audio to work though :(

Oblivion answered 1/11, 2016 at 21:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.