使用 MediaRecorder 将文件另存为 GIF

Joe*_*oel 5 javascript node.js html5-video html5-canvas html5-img

我正在开发一个屏幕捕获程序。目前,它将窗口的输出保存为webm. 我想知道是否可以将其保存为 GIF 而不是使用 MediaRecorder,它是本机MediaStream Recording API的一部分。

或者我是否必须依赖外部插件(例如 FFMPEG)来进行转换?如果能直接保存为 GIF 就太好了。

当我将文件的 和输出更改mimeType为. 录音不会产生任何输出(也没有错误)。由于在撰写本文时 MediaRecorder 还很新,因此可用的信息并不多。Mozilla 文档image/gif; codecs=vp9.gif

这是我的代码片段,类名为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!"));
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 Electron.js - 但这不是与 Electron 相关的问题(据我所知)。


2021 更新:支持的编解码器

文档/规范现在更加完整。但是,GIF 选项仍然不可用。

小智 3

MediaRecorder 不支持 image/gif mime-type。

您将需要一个 Javascript 库来编码为动画 GIF: https:
//github.com/mattdesl/gifenc

您还可以尝试 MediaStreamRecorder 而不是使用本机 MediaRecorder:
https://github.com/intercom/MediaStreamRecorder/blob/master/demos/gif-recorder.html

MediaStreamRecorder 文档中的注释:

“MediaStreamRecorder 可以在 Chrome 浏览器上将音频录制为 WAV,将视频录制为 WebM 或动画 gif 。”

也许这有帮助。

问候,奥米