Categories: Development

Cutting video into segments with timestamp as filename FFmpeg & PHP

Cutting a video into even segments and using the start and end time of the segment as its filename with FFmpeg and PHP.

For this you will need the length of the video in seconds as a loop is formed to represent each second. You can use the PHP function from here.

By using the Modulo operator the segment length can be determined at even intervals. To have the last segment filename be true to the length of the video in seconds, a check is done.

If the video is 35 seconds long and segment intervals of 10 seconds are wanted:

0-10
10-20
20-30
30-35

Instead of the last iteration misrepresenting the end time (30-40).

Cutting into segments

$time_seconds = 1780;

$segment_length = 30;

for ($i = 0; $i <= $time_seconds; $i++) {
    if ($i % $segment_length === 0) {
        (($i + $segment_length) > $time_seconds) ? $until = $time_seconds : $until = ($i + $segment_length);
        echo "ffmpeg -i input.mp4 -ss $i -t 30 cuts/{$i}-$until.mp4<br>";//Output query for debugging
    }
}

-ss is seek to position and -t is duration to limit the read.

Example output:

ffmpeg -i input.mp4 -ss 0 -t 30 cuts/0-30.mp4
ffmpeg -i input.mp4 -ss 30 -t 30 cuts/30-60.mp4
ffmpeg -i input.mp4 -ss 60 -t 30 cuts/60-90.mp4
ffmpeg -i input.mp4 -ss 90 -t 30 cuts/90-120.mp4
ffmpeg -i input.mp4 -ss 120 -t 30 cuts/120-150.mp4
ffmpeg -i input.mp4 -ss 150 -t 30 cuts/150-180.mp4
ffmpeg -i input.mp4 -ss 180 -t 30 cuts/180-210.mp4
ffmpeg -i input.mp4 -ss 210 -t 30 cuts/210-240.mp4
ffmpeg -i input.mp4 -ss 240 -t 30 cuts/240-270.mp4
....

Finding segments

To find the segment that contains the video at 355 seconds:

$find_segment = 355;//seconds

for ($i = 0; $i <= $time_seconds; $i++) {
    if ($i % $segment_length === 0) {
        if ($find_segment >= $i && $find_segment <= ($i + $segment_length)) {
            $until = $i + $segment_length;
            echo "cuts/{$i}-{$until}.mp4";//cuts/330-360.mp4
        }
    }
}

 

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago