使用 FFmpeg 和 WebAssembly 在浏览器内转码视频文件
The WebAssembly build of FFmpeg allows you to run this powerful video processing tool directly within the browser. In this blog post I explore FFmpeg.wasm and create a simple client-side transcoder that streams data into a video element, with a bit of RxJS thrown in for good measure.
FFmpeg 的 WebAssembly 构建版本允许你直接在浏览器中运行这个强大的视频处理工具。在这篇博客文章中,我探讨了 FFmpeg.wasm 并创建了一个简单的客户端转码器,它将数据流式传输到 video 元素中,还顺便加入了一些 RxJS。

FFmpeg.wasm
FFmpeg.wasm
FFmpeg is most often used via its command-line interface. For example, you can transcode an AVI file to an equivalent video file in MP4 as follows:
FFmpeg 最常通过其命令行界面使用。例如,你可以按如下方式将 AVI 文件转码为等效的 MP4 视频文件:
$ ffmpeg -i input.avi output.mp4
Let’s look at how you perform the same task within the browser …
让我们看看如何在浏览器中执行相同的任务……
FFmpeg.wasm is a WebAssembly port of FFmpeg, which you can install via npm and use within Node or the browser just like any other JavaScript module:
FFmpeg.wasm 是 FFmpeg 的 WebAssembly 移植版,你可以通过 npm 安装它,并像使用其他任何 JavaScript 模块一样在 Node 或浏览器中使用它:
$ npm install @ffmpeg/ffmpeg @ffmpeg/core
With FFmpeg.wasm installed, you can perform an equivalent transcoding entirely within the browser as follows:
安装 FFmpeg.wasm 后,你可以完全在浏览器中执行等效的转码,如下所示:
// fetch the AVI file
const sourceBuffer = await fetch("input.avi").then(r => r.arrayBuffer());
// create the FFmpeg instance and load it
const ffmpeg = createFFmpeg({ log: true });
await ffmpeg.load();
// write the AVI to the FFmpeg file system
ffmpeg.FS(
"writeFile",
"input.avi",
new Uint8Array(sourceBuffer, 0, sourceBuffer.byteLength)
);
// run the FFmpeg command-line tool, converting the AVI into an MP4
await ffmpeg.run("-i", "input.avi", "output.mp4");
// read the MP4 file back from the FFmpeg file system
const output = ffmpeg.FS("readFile", "output.mp4");
// ... and now do something with the file
const video = document.getElementById("video");
video.src = URL.createObjectURL(
new Blob([output.buffer], { type: "video/mp4" })
);
There’s a lot of interesting stuff going on here, so let’s dive into the details.
这里有很多有趣的内容,让我们...