Nuzzob
Nuzzob

Reputation: 411

Save video blob to filesystem electron/node js

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 !

Upvotes: 12

Views: 29786

Answers (3)

JeffD23
JeffD23

Reputation: 9298

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!') );

}

Upvotes: 23

posit labs
posit labs

Reputation: 9431

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)

Upvotes: 6

demian85
demian85

Reputation: 2494

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 :(

Upvotes: 0

Related Questions