Build a Node.js Image & Video Converter Using FFMPEG Stream API & ffmpeg-stream Library in Javascript Full Project For Beginners

 

 

FFmpeg-Stream

Travis Codecov npm

Node bindings to ffmpeg command, exposing stream based API.

CHANGELOG

Note: ffmpeg must be installed and available in PATH.

 

 

Examples

 

 

const { Converter } = require("ffmpeg-stream")
const { createReadStream, createWriteStream } = require("fs")
 
async function convert() {
  const converter = new Converter()
 
  // get a writable input stream and pipe an image file to it
  const input = converter.createInputStream({
    f: "image2pipe",
    vcodec: "mjpeg",
  })
  createReadStream(`${__dirname}/cat.jpg`).pipe(input)
 
  // create an output stream, crop/scale image, save to file via node stream
  converter
    .createOutputStream({
      f: "image2",
      vcodec: "mjpeg",
      vf: "crop=300:300,scale=100:100",
    })
    .pipe(createWriteStream(`${__dirname}/cat_thumb.jpg`))
 
  // same, but save to file directly from ffmpeg
  converter.createOutputToFile(`${__dirname}/cat_full.jpg`, {
    vf: "crop=300:300",
  })
 
  // start processing
  await converter.run()
}

 

const { Converter } = require("ffmpeg-stream")
 
const converter = new Converter()
 
converter
  .createOutputStream({ f: "image2pipe", vcodec: "mjpeg" })
  .pipe(new ExtractFrames("FFD8FF")) // use jpg magic number as delimiter
  .on("data", frame => {
    /* do things with frame (instance of Buffer) */
  })
  .on("end", () => {
    /* do things on complete */
  })
  .on("error", () => {
    /* do things on error */
  })

 

 

Images to Video

 

 

const { Converter } = require("ffmpeg-stream")
 
const frames = ["frame1.jpg", "frame2.jpg", ...etc]
 
const converter = new Converter() // create converter
 
// create input writable stream
const input = converter.createInputStream({ f: "image2pipe", r: 30 })
// output to file
converter.createOutputToFile("out.mp4", {
  vcodec: "libx264",
  pix_fmt: "yuv420p",
})
 
// for every frame create a function that returns a promise
frames
  .map(filename => () =>
    new Promise((resolve, reject) =>
      s3
        .getObject({ Bucket: "...", Key: filename })
        .createReadStream()
        .on("end", resolve)
        .on("error", reject)
        // pipe to converter, but don't end the input yet
        .pipe(input, { end: false })
    )
  )
  // reduce into a single promise, run sequentially
  .reduce((prev, next) => prev.then(next), Promise.resolve())
  // end converter input
  .then(() => input.end())
 
converter.run()

Leave a Reply