Use FFmpeg directly in your browser without any backend services!!

Transcode

transcode-demo

Source Code

<html>
  <head>
    <script src="/dist/ffmpeg.dev.js"></script>
    <style>
      html, body {
        margin: 0;
        width: 100%;
        height: 100%
      }
      body {
        display: flex;
        flex-direction: column;
        align-items: center;
      }
    </style>
  </head>
  <body>
    <h3>Upload a video to transcode to mp4 (x264) and play!</h3>
    <video id="output-video" controls></video><br/>
    <input type="file" id="uploader">
    <p id="message"></p>
    <script>
      const { createFFmpeg } = FFmpeg;
      const ffmpeg = createFFmpeg({ log: true });

      const transcode = async ({ target: { files } }) => {
        const message = document.getElementById('message');
        const { name } = files[0];
        message.innerHTML = 'Loading ffmpeg-core.js';
        await ffmpeg.load();
        await ffmpeg.write(name, files[0]);
        message.innerHTML = 'Start transcoding';
        await ffmpeg.transcode(name,  'output.mp4');
        message.innerHTML = 'Complete transcoding';
        const data = ffmpeg.read('output.mp4');
        ffmpeg.remove('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);
    </script>
  </body>
</html>

Supported Formats

  • mp4 (x264)
  • webm (vp8/vp9) (^0.8.0)
  • mp3 (^0.8.0)

ffmpeg.wasm provides simple to use APIs, to transcode a video you only need few lines of code:

const fs = require('fs');
const { createFFmpeg } = require('@ffmpeg/ffmpeg');

const ffmpeg = createFFmpeg({ log: true });

(async () => {
  await ffmpeg.load();
  await ffmpeg.write('test.avi', './test.avi');
  await ffmpeg.transcode('test.avi', 'test.mp4');
  fs.writeFileSync('./test.mp4', ffmpeg.read('test.mp4'));
  process.exit(0);
})();

Installation

$ npm install @ffmpeg/ffmpeg

As we are using the latest experimental features, you need to add few flags to run in Node.js

$ node --experimental-wasm-threads --experimental-wasm-bulk-memory transcode.js

Or, using a script tag in the browser (only works in Chrome):

<script src="https://unpkg.com/@ffmpeg/ffmpeg@0.8.3/dist/ffmpeg.min.js"></script>
<script>
  const { createFFmpeg } = FFmpeg;
  ...
</script>

Multi-thread

Starting from v0.8.0, multithreading is enabled and you can use this feature by passing -threads <NUM> (NUM < 8 ). For built-in functions like transcode(), you can pass it as 3rd argument.

// in transcode()
await ffmpeg.transcode('flame.avi', 'flame.mp4', '-threads 2');

// in run()
await ffmpeg.run('-i flame.avi -threads 2 flame.mp4');

Examples

#webassembly #web-development #programming #developer

FFmpeg for Browser and Node, Powered by WebAssembly
13.05 GEEK