ffmpeg实现web在线转码

通常我们使用MP4格式,但是MP4又分为“1.MPEG4(DivX)”、“2.MPEG4(Xvid)”、“3.AVC(H264)”三种类型。其中只有H264类型的视频才能进行html播放。
标签所支持的视频格式和编码:
MP4 = MPEG 4文件使用 H264 视频编解码器和AAC音频编解码器。
WebM = WebM 文件使用 VP8 视频编解码器和 Vorbis 音频编解码器。
Ogg = Ogg 文件使用 Theora 视频编解码器和 Vorbis音频编解码器。

浏览器支持情况:

格式IEFirefox     Opera Chrome  Safari
Ogg   No3.5+10.5+ 5.0+No
MPEG4 9.0+   NoNo 5.0+3.0+
WebMNo  4.0+10.6+  6.0+No

注释:Internet Explorer 8 以及更早的版本不支持 video  标签。

使用ffmpeg.wasm转码

预览地址:

https://demo.runoops.com/demo/ffmpegwasm/browser/transcode.html

1、原理:

ffmpeg.wasm 是 FFmpeg 的纯 WebAssembly / JavaScript 端口。它支持在浏览器内录制、转换和流式传输视频和音频。

Webassembly 的出现为前端转码提供可能。

2、html/js 代码

<h3>Upload a video to transcode to mp4 (x264) and play!</h3>
    <video id="output-video" controls></video><br/>
    <input type="file" id="uploader">
    <button onClick="cancel()">Cancel</button>
    <p id="message"></p>
    <script>
      const { createFFmpeg, fetchFile } = FFmpeg;
      let ffmpeg = null;

      const transcode = async ({ target: { files } }) => {
        if (ffmpeg === null) {
          ffmpeg = createFFmpeg({ log: true });
        }
        const message = document.getElementById('message');
        const { name } = files[0];
        message.innerHTML = 'Loading ffmpeg-core.js';
        if (!ffmpeg.isLoaded()) {
          await ffmpeg.load();
        }
        ffmpeg.FS('writeFile', name, await fetchFile(files[0]));
        message.innerHTML = 'Start transcoding';
        await ffmpeg.run('-i', name,  'output.mp4');
        message.innerHTML = 'Complete transcoding';
        const data = ffmpeg.FS('readFile', 'output.mp4');

        const video = document.getElementById('output-video');
        video.src = URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' }));
      }
      const elm = document.getElementById('uploader');
      elm.addEventListener('change', transcode);

      const cancel = () => {
        try {
          ffmpeg.exit();
        } catch(e) {}
        ffmpeg = null;
      }
    </script>

3、结果

页面可以正常加载和上传,但是在转码过程中报错了:

ReferenceError: SharedArrayBuffer is not defined,

所以需要解决SharedArrayBuffer报错。

可以看到SharedArrayBuffer是支持谷歌浏览器79版本以上

那么,为什么这里会出现SharedArrayBuffer is not defined的报错信息呢?

原因是因为谷歌浏览器的安全策略机制改变了。

2017.7月(Chrome 60)引入 SharedArrayBuffer。

2021.7月(Chrome 92)限制 SharedArrayBuffer只能在 cross-origin isolated 页面使用。

Android Chrome 88 也进行了同样的限制。

从上述结论中,可以知道在60-91的版本的浏览器是可以正常打开的。

如何设置跨域隔离启用 SharedArrayBuffer

4、效果

在控制台中可以看到读取文件和转码进程,而且页面可以正常的显示视频并播放。

Captcha Code

0 笔记

分享笔记

Inline Feedbacks
View all notes