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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago