我正在开发一个屏幕捕获程序。目前,它将窗口的输出保存为 webm
.我想知道是否可以将其保存为 GIF,而不是使用 MediaRecorder,它是 native MediaStream Recording API 的一部分。 .
或者我是否必须依赖外部插件(如 FFMPEG)来进行转换?能够直接将其保存为 GIF 会很整洁。
当我更改 mimeType
至image/gif; codecs=vp9
并将文件输出到.gif
.录音没有产生任何输出(也没有错误)。由于 MediaRecorder 在撰写本文时还很新,因此可用的信息并不多。 Mozilla Docs
这是我的代码片段,类名为 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!"));
}
}
我正在使用 Electron.js - 但这不是与 Electron 相关的问题(据我所知)。2021 年更新:Supported codecs
Docs/spec 现在更完整了。但是,GIF 选项仍然不可用。
最佳答案
MediaRecorder 不支持 image/gif mime-type。
您将需要一个 Javascript 库来编码为动画 GIF:
https://github.com/mattdesl/gifenc
您也可以尝试使用 MediaStreamRecorder 而不是使用 native MediaRecorder:
https://github.com/intercom/MediaStreamRecorder/blob/master/demos/gif-recorder.html
MediaStreamRecorder 文档中的注释:
"MediaStreamRecorder can record audio as WAV and video as either WebM or animated gif on Chrome browser."
也许这有帮助。
问候,
臣
关于javascript - 使用 MediaRecorder 将文件另存为 GIF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60637172/