Using fluent-ffmpeg to work with videos in NodeJS

Introduction

ffmpeg is a popular library that provides APIs for extracting information and manipulating videos. It supports various programming languages such as JavaScript, Ruby, and more. In this article, I'll give you a simple example of how to use ffmpeg to create thumbnails from videos and resize videos in NodeJS with TypeScript.

Prerequisites

Before we start, you need to install ffmpeg. The installation process depends on your operating system. If you're using Ubuntu, it's straightforward:

sudo apt install ffmpeg


Next, set up your NodeJS Typescript project. After that, install the package `fluent-ffmpeg`. This package will serve as the interface for interacting between NodeJS and the previously installed `ffmpeg`.

yarn add fluent-ffmpeg


Source Code

Update the `main.ts` file with the following content:

import * as ffmpeg from 'fluent-ffmpeg'

const srcVideo = 'path/test.mp4'
const outputVideo = 'path/test-resized.mp4'
const outputScreenshot = 'path/screenshot.jpg'
const size = '200x100' //pixels for resolution

// get first frame to create thumbnail
ffmpeg(srcVideo)
.seekInput('00:00.000')
.output(outputScreenshot)
.outputOptions(
'-frames',
'1' // get 1 image
)
.on('end', () => {
console.log('Completed')
ffmpeg.ffprobe(outputScreenshot, (err, metadata) => {
console.log('Output info', err, metadata.format)
})
})
.run()

// resize video
ffmpeg(srcVideo)
.size(size)
.on('end', () => {
console.log('Completed')
})
.save(outputVideo)

  • You can see that the deployment code is relatively easy to understand. Here, I'm using ffmpeg to create a thumbnail by capturing the first frame of a video and saving it as an image. 
  • To resize a video, you just need to provide the source video and the desired dimensions.
  • Make sure to adjust the directory paths for `srcVideo`, `outputVideo`, and `outputScreenshot`, as well as the `size`, to suit your needs.


Don't hesitate to leave your thoughts in the comments section, and remember to like, share, and follow for more insightful content in the future!

Comments

Popular posts from this blog

Kubernetes Practice Series

NodeJS Practice Series

Docker Practice Series

Deploying a NodeJS Server on Google Kubernetes Engine

React Practice Series

Setting up Kubernetes Dashboard with Kind

Sitemap

Using Kafka with Docker and NodeJS

A Handy Guide to Using Dynamic Import in JavaScript

Create API Gateway with fast-gateway