Use MediaRecorder To Save File As GIF

1.8k views Asked by At

I'm working on a screen-capture program. Currently, it's saving the output of the window as webm. I'm wondering if it's possible to save it as GIF instead using MediaRecorder, which is part of the native MediaStream Recording API.

Or do I have to rely on an external plugin such as FFMPEG to do the conversion for this? Would be neat to be able to save it directly as GIF.

When I'm changing the mimeType to image/gif; codecs=vp9 and the output of the file to .gif. The recording isn't producing any output (no errors either). Since MediaRecorder is quite new as of writing this, there isn't very much information available. Mozilla Docs

This is a snippet of my code, class is called Recorder:

public static readonly mimeType: string = "video/webm; codecs=vp9";
public mediaRecorder?: MediaRecorder;
public videoElement: HTMLVideoElement = <HTMLVideoElement>document.querySelector("video");
...

async selectSource(source: Electron.DesktopCapturerSource): Promise<any> {
    ...
    const stream = await navigator.mediaDevices.getUserMedia(<MediaStreamConstraints>constraints);
    this.videoElement.srcObject = stream;

    const streamOptions = { mimeType: `${Recorder.mimeType}` };

    this.mediaRecorder = new MediaRecorder(stream, streamOptions);
    this.mediaRecorder.ondataavailable = () => this.storeAvailableData;
    this.mediaRecorder.onstop = () => this.saveRecording();
}

storeAvailableData(e:any): void {
    console.log("video data available");
    this.recordedChunks.push(e.data);
}

async saveRecording(): Promise<any> {
    //blob is of type any due to @typings not yet updated.
    const blob:any = new Blob(this.recordedChunks, {
        type: `${Recorder.mimeType}`
    });

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

    const { filePath } = await this.dialog.showSaveDialog({
        buttonLabel: "Save video",
        defaultPath: `vid-${Date.now()}.webm`
    });

    if (filePath) {
        writeFile(filePath, buffer, () => console.log("video saved!"));
    }
}

I'm using Electron.js - but this is not a Electron-related problem (as far as I can tell).


Update 2021: Supported codecs

Docs/spec is now somewhat more complete. However, GIF option is still not available.

1

There are 1 answers

1
omi On BEST ANSWER

image/gif mime-type is not supported in MediaRecorder.

You will need a Javascript library to encode as Animated GIF:
https://github.com/mattdesl/gifenc

You can also try MediaStreamRecorder instead of using native MediaRecorder:
https://github.com/intercom/MediaStreamRecorder/blob/master/demos/gif-recorder.html

note from MediaStreamRecorder docs:

"MediaStreamRecorder can record audio as WAV and video as either WebM or animated gif on Chrome browser."

Maybe this helps.

Regards, omi