How to Trim, Cut, and Extract Your Video Clips Using FFmpeg

Cutting and trimming. It’s the story of a video editor’s life. Anyone whose job entails managing video content probably performs these two tasks more than any other editing process. While cutting and trimming are relatively basic tasks, they still demand precision and accuracy in order for videos to maintain a professional level of quality.

These tasks may not demand deep expertise to execute, but they can certainly be time-consuming if they have to be performed on a large volume of videos. In this tutorial, we’ll dive into two methods for programmatically trimming, cutting, and extracting video clips—one using the free video editing library FFmpeg, and another that uses the Editframe API. Ultimately, this tutorial will be critical for developing your video editing skills.

We’ll see how to trim the start, end, or middle of a video to create shorter segments, then take these shorter segments and stitch them together, or simply use the shorter clips as standalone content.

Here are just a handful of situations in which the skills you’ll learn in this tutorial would be extremely handy:

  • You need a short clip of a video to promote on social media
  • You’re a musician who needs a short promotional video clip
  • You’re a vlogger and you want to make quick promotional videos for Instagram posts or TikTok videos
  • You want to accomplish any of these editing tasks without using bulky desktop video editors like Final Cut or iMovie
  • You have lots and lots of videos to trim or cut, and better things to do with your life than sit in front of a video editor

Ready? Let’s go.

File assets

Here is a sample video file provided by pexels.com that we will use in this tutorial:

video.mp4

Part 1: Using FFmpeg

First, we’ll walk through this workflow using FFmpeg.

Required Tools

  • Sample video file overlay (provided above)
  • FFmpeg: (You’ll need to install FFmpeg and set up the appropriate environment variables before beginning this tutorial)

Here is the FFmpeg command to trim the video from a specific start and end time:

ffmpeg -ss 00:00:02 -to  00:00:05  \
 -i video.mp4 -c copy trim-1.mp4

Let’s break down what this code is doing.

  • In this line, we trim the video from the 2-second mark to the 5-second mark using this format 00:00:02:00 to 00:00:05:00:
ffmpeg -ss 00:00:02 -to  00:00:05
  • In this line, we import the video file, then copy the video and audio stream intro trim-1.mp4 :
 -i video.mp4 -c copy trim-1.mp4

Here is the output video from the FFmpeg command:

trim-1.mp4

With start time and duration (FFmpeg)

Now let’s do the same thing, only this time we’ll specify a start time and a duration rather than a starting and ending timestamps. Here’s the FFmped command to do that:

ffmpeg -i video.mp4 \
-ss 00:00:02 -t 00:00:03 \
-c:v copy -c:a copy trim-2.mp4

You know the drill. Let’s break it down.

  • In this line, we import the video file:
ffmpeg -i video.mp4 \
  • Here, we trim the video from the 1-second mark, and specify a 3-second duration (this will extract the video from 00:02 to 00:05, and remove the rest):
-ss 00:00:02 -t 00:00:03 \
  • In this line, we import the video file and copy the video and audio streams into trim-2.mp4:
-c:v copy -c:a copy trim-2.mp4

Here is the output video from using the FFmpeg command:

trim-2.mp4

Part 2: Using Editframe

Now let’s perform the same task using Editframe instead of FFmpeg.

Required tools:

  • Node.js installed on your machine (v16+)
  • Editframe API Token (you can create an account from this link)

*No need to have FFmpeg installed on your machine

  • Create a folder fir your project:
mkdir editframe-trim-video
  • Initialize the Node.js project:
cd editframe-trim-video && yarn init -y
  • Install the Editframe Node.js SDK:
yarn add @editframe/editframe-js
  • Create a create-video.js file to merge our videos into one:
const { Editframe } = require("@editframe/editframe-js");

const main = async () => {
  const editframe = new Editframe({
    develop: true,
    clientId: "YOUR_EDITFRAME_CLIENT_ID",
    token: "YOUR_EDITFRAME_TOKEN",
  });
  const composition = await editframe.videos.new({
    dimensions: {
      height: 1080,
      width: 1920,
    },
    duration: 7
  });

  await composition.addVideo(
    // file
    `${__dirname}/video.mp4`,
    // config
    {
      trim: {
        // start time of the video where you want to cut in seconds
        start: 2,
        // end time of the video where you want to cut in seconds
        end: 5,
      },
    }
  );
  const video = await composition.encodeSync();
  console.log(video);
};

main();

Let’s dive into the code in this file.

  • Here, we initialize an Editframe instance with our Editframe Token (obtained by creating an Editframe application). We also set the develop key to true, which tells Editframe that we want to open the output video in new tab when encoding has finished:
const editframe = new Editframe({
    develop: true,
    clientId: "YOUR_EDITFRAME_CLIENT_ID",
    token: "YOUR_EDITFRAME_TOKEN",
  });
const composition = await editframe.videos.new({
    dimensions: {
      height: 1080,
      width: 1920,
    },
    duration: 7
  });
  • In these lines, we add the video file path to the video composition using the composition.addVideo method. We also trim the video from start (:02) to end (:05) seconds:
await composition.addVideo(
    // file
    `${__dirname}/video.mp4`,
    // config
    {
      trim: {
        // start time of the video where you want to cut in seconds
        start: 2,
        // end time of the video where you want to cut in seconds
        end: 5,
      },
    }
  );
const video = await composition.encodeSync();
console.log(video);
  • Now, run the video script:
node create-video

Here is the output video from the Editframe API:

editframe-trim.mp4

Note: Editframe also lets you add transitions, filter and trim videos, and do much more. You can learn about other ways to use Editframe from the Editframe API docs.

Part 2a: Using the Editframe Toolbox

Editframe Video Tools provide high-level video processing endpoints for one-off tasks. Using the Trim toolbox, we can execute the editing process demonstrated above by making a simple API call.

We can define a start time and duration in seconds using the request parameters on the Trim endpoint POST /v2/videos/trim. Here is how we would trim a video executed above with curl:

curl --location -g --request POST 'https://api.editframe.com/v2/videos/trim' \
--header 'Authorization: Bearer YOUR_API_TOKEN' \
--form 'video=@"/Users/mac/Downloads/video.mp4"' \
--form 'start="2"' \
--form 'duration="3"'

In return, we receive the following response:

{
	"id":"anq9kaYb84",
	"timestamp":1670961863,
	"status":"processing"
}

We can also execute this API call using Node and native libraries:

import fs from 'fs'
import FormData from 'form-data'
import fetch, { Headers } from 'node-fetch'

var myHeaders = new Headers()
myHeaders.append('Authorization', 'Bearer YOUR_API_TOKEN')

var formdata = new FormData()
formdata.append('video', fs.createReadStream('/Users/mac/video.mp4'))
formdata.append('start', '2')
formdata.append('duration', '3')

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: formdata,
  redirect: 'follow',
}

fetch('https://api.editframe.com/v2/videos/trim', requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log('error', error))

Comparing the FFmpeg and Editframe API output videos

Here is the video comparison between Editframe and FFmpeg:

compare.mp4

© 2024 Editframe
Making video creation easier for software developers.