Published on

Trim a Media File Using Start and Stop Times with FFmpeg

Authors
  • avatar
    Name
    Hieu Cao
    Twitter

Why Trim Media Files?

Trimming media files is essential for:

  • Removing Unnecessary Content: Eliminate unwanted sections from videos or audio files.
  • Creating Clips: Extract specific parts for sharing or analysis.
  • Optimizing File Size: Reduce the length to save storage space.

What Does Trimming Mean?

Trimming involves cutting a media file to include only the specified portion between a start time and an end time. With FFmpeg, this process is efficient and lossless when no re-encoding is involved.


Trimming a Media File with FFmpeg

Basic Command

The -ss and -to options specify the start and stop times:

ffmpeg -i input.mp4 -ss 00:01:00 -to 00:02:00 -c copy output.mp4
  • -i input.mp4: The source file.
  • -ss 00:01:00: Start trimming at 1 minute.
  • -to 00:02:00: Stop trimming at 2 minutes.
  • -c copy: Copy streams without re-encoding for faster processing.

Example: Extract a 30-Second Clip

ffmpeg -i video.mp4 -ss 00:00:30 -to 00:01:00 -c copy clip.mp4

Trimming with Re-Encoding

If you need to re-encode the file (e.g., for format compatibility):

ffmpeg -i input.mp4 -ss 00:01:00 -to 00:02:00 -c:v libx264 -crf 23 -preset fast -c:a aac -b:a 128k output.mp4
  • -c:v libx264: Use the H.264 codec for video.
  • -crf 23: Set the quality factor (lower is better).
  • -preset fast: Optimize the encoding speed.
  • -c:a aac: Use the AAC codec for audio.
  • -b:a 128k: Set the audio bitrate.

Verifying the Trimmed File

To check the duration of the output file, use FFprobe:

ffprobe -i output.mp4

Look for the "Duration" field in the output.


Best Practices

  1. Use Accurate Timestamps: Ensure start and stop times are precise.
  2. Avoid Re-Encoding: Copy streams for faster trimming and no quality loss unless necessary.
  3. Test Output Files: Verify that the trimmed content meets your requirements.

Conclusion

Trimming media files with FFmpeg is a straightforward process, whether you're preparing clips for social media or optimizing files for storage. With just a few commands, you can precisely extract the content you need. Start trimming your media files today!