Implement a QuickTime media-trimming experience in your macOS app.
AVPlayer to provide a playback experience like that of QuickTime Player in macOS. However,
AVPlayer not only provides the QuickTime playback interface, but it also provides the QuickTime media-trimming experience.
Verify that Trimming Is Allowed
Before attempting to put the player into trimming mode, verify that trimming is allowed by querying the player view’s
can property. This property returns
false if you’re playing an asset delivered over HTTP Live Streaming or if the asset is content protected. If you’re presenting a menu item to initiate trimming, a good place to perform this check is in the
validate method of
NSDocument, so that the menu item can automatically be disabled if trimming is disallowed.
Enter Trimming Mode
After you’ve determined that the media supports trimming, you call the
begin. This method takes a completion block that you use to determine whether the user completed the trim or canceled the operation.
Transcode the Trimmed Asset
AVAsset is an immutable object, you may be wondering how its duration is changed when you click the Trim button. Trimming relies on a feature of
AVPlayer to adjust the presented time range.
AVPlayer provides the
forward properties that set the in and out points for a media item. It doesn’t change the underlying asset, but essentially changes your effective view of it. To save the results of the user’s trim operation, you export a new copy of the asset, trimming it to the specified times. The simplest way to do this is to use
AVAsset, which provides a simple and performant way for you to transcode the media of an asset. You create a new export session, passing it the asset to export along with a transcoding preset to use.
This example uses a preset to export the media as a 720p, M4V file, but
AVAsset supports a wide variety of export presets. To find out what export session presets are supported for the current asset, you can use the session’s
export class method, passing it the asset you want to export. This method returns an array of valid presets that you can use in your export.
Select the Trimmed Asset
To export only the content the user trimmed, you use the current player item’s reverse and forward end-time values to define a
CMTime to set on the export session.
Export the Trimmed Asset
To perform the actual export operation, you call its
export method. Check the status of the export session in the completion handler and handle completion and failure cases.