One of the essential skills in video editing is trimming videos. Trimming involves selecting a portion of the video clip and removing the unwanted parts to create a seamless story. Another use case is repurposing content. For example, extracting 15 or 30 second clips from a longer video to create social media shorts.

If you have a large volume of videos that need to be trimmed you might want to programmatically trim a collection of videos. This is possible using the Shotstack Edit API and their PHP video editing SDK.

And in this article I will show you how to do it. The article is divided into two parts and will show you:

  • How to trim a single video
  • How to trim multiple videos from a list

About Shotstack and PHP video editing

Shotstack provides a cloud-based video editing API. Building media applications at scale that can edit and trim videos can take hours, and rendering requires significant resources. But with the help of Shotstack's rendering infrastructure, media applications can be built and scaled in lass than 15 minutes as this article will demonstrate.

PHP is a popular server-side scripting language that is widely used for web development but isn't often associated with video editing. However, with the Shotstack PHP SDK, developers can easily integrate video editing capabilities into their PHP applications. The SDK provides a set of tools and features that make it easy to create and edit videos programmatically.

Requirements

  • A Shotstack API key - Sign up for a free developer account to get a free to use key.
  • PHP 8 - you can likely use different versions of PHP, but this tutorial was written and tested using PHP 8.1.2.
  • Shotstack PHP SDK - you can install the composer package using the following command:
composer require shotstack/shotstack-sdk-php

Create a PHP script to trim a single video

Shotstack API follows familiar principles of desktop editing software with a timeline, tracks, and clips. A timeline represents the entire video and is composed of one or more tracks that contain one or more media clips that can be video, images, audio or text.

A clip can have a start time, length (duration) and a trim property to cut the start off the clip. Using these settings you can trim a video to the desired length and start time.

Follow the steps below to set this up using the Shotstack PHP SDK.

Import the SDK packages

In your preferred text editor or IDE, create a PHP script file. You can call it whatever you like, but for this tutorial, we will create a file named trim.php. Open the file and let's begin editing.

If you didn't already install the Shotstack PHP video editing SDK using the composer command above in the same folder as your script. Then import the packages to be used in our script using teh PHP use statement.

Copy the following to your trim.php file:

<?php
require 'vendor/autoload.php';

use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;
use Shotstack\Client\Model\Edit;
use Shotstack\Client\Model\Output;
use Shotstack\Client\Model\Timeline;
use Shotstack\Client\Model\Track;
use Shotstack\Client\Model\Clip;
use Shotstack\Client\Model\VideoAsset;
?>

Set up the API client

Then add the following code, configuring the Shotstack API client with the API URL and key from the Shotstack dashboard:

$config = Configuration::getDefaultConfiguration()
->setHost('https://api.shotstack.io/stage')
->setApiKey('x-api-key', 'YOUR_KEY_HERE'); // use the sandbox API key from the dashboard

$client = new EditApi(null, $config);

Replace YOUR_KEY_HERE with the sandbox API key provided, which is free for testing and development.

Trim the video clip

We will need a video file to trim. You do this by providing the URL of a video file that is hosted online. The URL must either be public or accessible using a signed URL or URL based security method.

For this tutorial, we will use the following video of a skateboarder, which is 27 seconds long. You can replace this with any video of your choice of course.

Let's cut to the part of the video where the skateboarder jumps over the table at around second 5. To trim the start of the video, we will add the trim property, in seconds, to a video asset which will make the video start from the in point.

Let's get rid of the first 3 seconds of the video by adding the following code to create a VideoAsset using the video URL and trim the first 3 seconds from the start:

$videoAsset = new VideoAsset();
$videoAsset
->setSrc("https://d1uej6xx5jo4cd.cloudfront.net/skater.hd.mp4")
->setTrim(3);

Next, we need to create a Clip named $videoClip which will contain the $videoAsset we just created. We can set up various parameters, including length (the amount of time to play for) and start time (when on the timeline the clip will play from).

We will cut the section after the skateboarder lands, which is around 10 seconds. To do that, we will set the length to 8 seconds. This will effectively trim the end of the original video clip from second 11 (3 + 8). We set start to 0 to start the clip from the beginning of the timeline.

$videoClip = new Clip();
$videoClip
->setAsset($videoAsset)
->setLength(8)
->setStart(0);

Add the clip to the timeline

Next, add the $videoClip to a track $track and then add the $track to the $timeline like this:

$track = new Track();
$track
->setClips([$videoClip]);

$timeline = new Timeline();
$timeline
->setTracks([$track]);

Note that a track accepts an array of clips, so you can add multiple clips to a track. The timeline accepts an array of tracks, so you can add multiple tracks to a timeline. This is useful for creating complex video edits with multiple layers.

Prepare the final edit and output

Next, configure the video output - set the output format to mp4 and teh resolution to hd, which outputs a 1280 x 720 pixel (720p) video. The final step is to add the timeline and output to the $edit:

$output = new Output();
$output
->setFormat('mp4')
->setResolution('hd');

$edit = new Edit();
$edit
->setTimeline($timeline)
->setOutput($output);

Send the edit to the API for rendering

Finally, the API is used to trim and render the video. The Shotstack SDK handles the conversion of objects to JSON, POSTing everything to the API, and adding the key to the request header.

try {
$response = $client->postRender($edit)->getResponse();
} catch (ApiException $e) {
die('Request failed: ' . $e->getMessage() . $e->getResponseBody());
}

echo $response->getMessage() . "\n";
echo ">> render id: " . $response->getId() . "\n";

Final PHP trim video script

Below is the final code which should now be added to your trim.php file:

<?php
require 'vendor/autoload.php';
use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;
use Shotstack\Client\Model\Edit;
use Shotstack\Client\Model\Output;
use Shotstack\Client\Model\Timeline;
use Shotstack\Client\Model\Track;
use Shotstack\Client\Model\Clip;
use Shotstack\Client\Model\VideoAsset;

$config = Configuration::getDefaultConfiguration()
->setHost('https://api.shotstack.io/stage')
->setApiKey('x-api-key', 'YOUR_KEY_HERE'); // your API key
$client = new EditApi(null, $config);

$videoAsset = new VideoAsset();
$videoAsset
->setSrc("https://d1uej6xx5jo4cd.cloudfront.net/skater.hd.mp4")
->setTrim(3);

$videoClip = new Clip();
$videoClip
->setAsset($videoAsset)
->setLength(8)
->setStart(0);

$track = new Track();
$track
->setClips([$videoClip]);

$timeline = new Timeline();
$timeline
->setTracks([$track]);

$output = new Output();
$output
->setFormat('mp4')
->setResolution('hd');

$edit = new Edit();
$edit
->setTimeline($timeline)
->setOutput($output);

try {
$response = $client->postRender($edit)->getResponse();
} catch (ApiException $e) {
die('Request failed: ' . $e->getMessage() . $e->getResponseBody());
}

echo $response->getMessage() . "\n";
echo ">> render id: " . $response->getId() . "\n";
?>

Run the trim video PHP script

With everything set up, run the script from the command line like this:

php trim.php

If the render request is successful, the API will return the rendered id, which can be used to get the render status. The output should look like this:

Render Successfully Queued
>> render id: 5ed30fb5-51c3-4873-9aa3-9cb4b2066568

Check the render status and output URL

The video render will take a few seconds to complete wo we will need to check its status. To check the status we need another script which will call the API render status endpoint. Create a file called status.php and use the following code:

<?php
require 'vendor/autoload.php';

use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;

$config = Configuration::getDefaultConfiguration()
->setHost('https://api.shotstack.io/stage')
->setApiKey('x-api-key', 'YOUR_KEY_HERE'); // your API key

$client = new EditApi(null, $config);
$response = $client->getRender($argv[1], false, true)->getResponse();

echo "\nStatus: " . strtoupper($response->getStatus()) . "\n\n";

if ($response->getStatus() == 'done') {
echo ">> Asset URL: " . $response->getUrl() . "\n";
}
?>

Then run the script using the following command:

php status.php {RENDER_ID}

Replace {RENDER_ID} with the ID returned from the trim.php script, like this:

php status.php 5ed30fb5-51c3-4873-9aa3-9cb4b2066568

Run the status.php script every few seconds until the status is done and a URL is returned, the output should look like this:

Status: DONE

>> Asset URL: https://shotstack-api-stage-output.s3-ap-southeast-2.amazonaws.com/zysxdnk0f1/5ed30fb5-51c3-4873-9aa3-9cb4b2066568.mp4

Now open the returned URL in a browser or download it to view the trimmed video:

Automate trimming multiple videos using PHP

As shown above, we successfully trimmed a video using PHP and an API. If we only wanted to trim a single video, we could have done it manually using FFmpeg or desktop video editing software. However, if we have a list of videos that need to be trimmed, it would be time-consuming to do it manually. With the Shotstack Edit API we can automate the process and trim multiple videos at the same time.

To demonstrate automated video trimming, we will use PHP to trim the following list of videos:

https://cdn.shotstack.io/au/v1/msgtwx8iw6/d724e03c-1c4f-4ffa-805a-a47aab70a28f.mp4
https://cdn.shotstack.io/au/v1/msgtwx8iw6/b03c7b50-07f3-4463-992b-f5241ea15c18.mp4
https://cdn.shotstack.io/au/stage/c9npc4w5c4/d2552fc9-f05a-4e89-9749-a87d9a1ae9aa.mp4
https://cdn.shotstack.io/au/v1/msgtwx8iw6/c900a02f-e008-4c37-969f-7c9578279100.mp4

In the same folder as before, create a new PHP file named batch.php. Select the file and paste the following code:

<?php
require 'vendor/autoload.php';
use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;
use Shotstack\Client\Model\Edit;
use Shotstack\Client\Model\Output;
use Shotstack\Client\Model\Timeline;
use Shotstack\Client\Model\Track;
use Shotstack\Client\Model\Clip;
use Shotstack\Client\Model\VideoAsset;

$config = Configuration::getDefaultConfiguration()
->setHost('https://api.shotstack.io/stage')
->setApiKey('x-api-key', 'YOUR_KEY_HERE'); // use the sandbox API key from the dashboard

$urls = [
'https://cdn.shotstack.io/au/v1/msgtwx8iw6/d724e03c-1c4f-4ffa-805a-a47aab70a28f.mp4',
'https://cdn.shotstack.io/au/v1/msgtwx8iw6/b03c7b50-07f3-4463-992b-f5241ea15c18.mp4',
'https://cdn.shotstack.io/au/stage/c9npc4w5c4/d2552fc9-f05a-4e89-9749-a87d9a1ae9aa.mp4',
'https://cdn.shotstack.io/au/v1/msgtwx8iw6/c900a02f-e008-4c37-969f-7c9578279100.mp4'
];

$client = new EditApi(null, $config);

foreach ($urls as $url)
{
$videoAsset = new VideoAsset();
$videoAsset->setSrc($url)
->setTrim(3);

$videoClip = new Clip();
$videoClip ->setAsset($videoAsset)
->setLength(6)
->setStart(0);

$track = new Track();
$track
->setClips([$videoClip]);

$timeline = new Timeline();
$timeline
->setTracks([$track]);

$output = new Output();
$output
->setFormat('mp4')
->setResolution('hd');

$edit = new Edit();
$edit
->setTimeline($timeline)
->setOutput($output);

try {
$response = $client->postRender($edit)->getResponse();
} catch (ApiException $e) {
die('Request failed: ' . $e->getMessage() . $e->getResponseBody());
}

echo $response->getMessage() . "\n";
echo ">> render id: " . $response->getId() . "\n";
}
?>

Remember to replace YOUR_KEY_HERE and then run the script using the following command:

php batch.php

This time you should see multiple render IDs returned, one for each video:

Render Successfully Queued
>> render id: f69cdfa7-948e-40f7-9842-01e86fc8b1d5
Render Successfully Queued
>> render id: a027f247-a0cb-4ed2-8b40-02b4f99f549e
Render Successfully Queued
>> render id: 1ee31769-bf52-4560-bd46-43eba5c076bd
Render Successfully Queued
>> render id: 6c40dd0e-08c5-4cb5-aa35-e6f4238fa355

Run the status.php file we created earlier to check the render status of each render, replacing {RENDER_ID} with the render ID returned from the batch.php script:

php status.php {RENDER_ID}

After a few seconds each video will be trimmed and ready to view or download.

Final Thoughts

In this article, we learned how to trim videos using PHP and the Shotstack API. We also learned how trimming videos at scale can be automated and offloaded to a cloud based API, saving developers valuable time and resources.

The script we created is very simple and could be made more useful by specifying different trim, start and length values for each video. This could be done by creating a CSV file with the video URLs and values and then reading the file and processing each video in a loop.

Once you have mastered trimming videos, you can move on to more advanced video editing techniques such as adding text, transitions, effects, and audio to create more engaging and professional videos and build your own automated workflows and video applications. Have a look at more of our developer guides and documentation to learn more.

Get started with Shotstack's video editing API in two steps:

  1. Sign up for free to get your API key.
  2. Send an API request to create your video:
    curl --request POST 'https://api.shotstack.io/v1/render' \
    --header 'x-api-key: YOUR_API_KEY' \
    --data-raw '{
    "timeline": {
    "tracks": [
    {
    "clips": [
    {
    "asset": {
    "type": "video",
    "src": "https://shotstack-assets.s3.amazonaws.com/footage/beach-overhead.mp4"
    },
    "start": 0,
    "length": "auto"
    }
    ]
    }
    ]
    },
    "output": {
    "format": "mp4",
    "size": {
    "width": 1280,
    "height": 720
    }
    }
    }'
Emad Bin Abid

BY EMAD BIN ABID
13th February 2024

Studio Real Estate
Experience Shotstack for yourself.
SIGN UP FOR FREE

You might also like

Convert MP4 video to GIF using PHP

Convert MP4 video to GIF using PHP

Emad Bin Abid
Convert MP4 video to MP3 audio using PHP

Convert MP4 video to MP3 audio using PHP

Emad Bin Abid