Class

AVPlayerItem

An object used to model the timing and presentation state of an asset played by the player.

Declaration

@interface AVPlayerItem : NSObject

Overview

An AVPlayerItem stores a reference to an AVAsset object, which represents the media to be played. If you need to access information about the asset before you enqueue it for playback, you can use the methods of the AVAsynchronousKeyValueLoading protocol to load the values you need. Alternatively, AVPlayerItem can automatically load the needed asset data for you by passing the desired set of keys to its initWithAsset:automaticallyLoadedAssetKeys: initializer. When the player item is ready to play, those asset properties will have been loaded and are ready for use.

AVPlayerItem is a dynamic object. In addition to its property values that can be changed by you, many of its read-only property values can be changed by the associated AVPlayer during the item’s preparation and playback. You can use Key-value observing to observe these state changes as they occur. One of the most important player item properties to observe is its status. The status indicates if the item is ready for playback and generally available for use. When you first create a player item, its status has a value of AVPlayerItemStatusUnknown, meaning its media hasn’t been loaded and has not yet been enqueued for playback. Associating a player item with an AVPlayer immediately begins enqueuing the item’s media and preparing it for playback, but you need to wait until its status changes to AVPlayerItemStatusReadyToPlay before it’s ready for use. The following code example illustrates how to register and be notified of status changes:

- (void)prepareToPlay {
    NSURL *url = <#Asset URL#>
    // Create asset to be played
    asset = [AVAsset assetWithURL:url];
    NSArray *assetKeys = @[@"playable", @"hasProtectedContent"];
 
    // Create a new AVPlayerItem with the asset and an
    // array of asset keys to be automatically loaded
    playerItem = [AVPlayerItem playerItemWithAsset:asset
                      automaticallyLoadedAssetKeys:assetKeys];
 
    NSKeyValueObservingOptions options =
        NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew;
 
    // Register as an observer of the player item's status property
    [playerItem addObserver:self
                 forKeyPath:@"status"
                    options:options
                    context:&PlayerItemContext];
 
    // Associate the player item with the player
    player = [AVPlayer playerWithPlayerItem:playerItem];
}

The prepareToPlay method registers to observe the player item’s status property using the addObserver:forKeyPath:options:context: method. You should call this method before associating the player item with the player to make sure you capture all state changes to the item’s status.

To be notified of changes to the status, you need to implement the observeValueForKeyPath:ofObject:change:context: method. This method is invoked whenever the status changes giving you the chance to take some action in response (see example).

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context {
    // Only handle observations for the PlayerItemContext
    if (context != &PlayerItemContext) {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        return;
    }
 
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = AVPlayerItemStatusUnknown;
        // Get the status change from the change dictionary
        NSNumber *statusNumber = change[NSKeyValueChangeNewKey];
        if ([statusNumber isKindOfClass:[NSNumber class]]) {
            status = statusNumber.integerValue;
        }
        // Switch over the status
        switch (status) {
            case AVPlayerItemStatusReadyToPlay:
                // Ready to Play
                break;
            case AVPlayerItemStatusFailed:
                // Failed. Examine AVPlayerItem.error
                break;
            case AVPlayerItemStatusUnknown:
                // Not ready
                break;
        }
    }
}

The example retrieves the new status from the change dictionary and switches over its value. If the player item’s status is AVPlayerItemStatusReadyToPlay, then it’s ready for use. If a problem was encountered while attempting to load the player item’s media, the status will be AVPlayerItemStatusFailed. You can get the NSError providing the details of the failure by querying the player item’s error property.

Topics

Creating a Player Item

- initWithURL:

Initializes a player item with a given URL.

+ playerItemWithURL:

Returns a new player item, prepared to use a given URL.

- initWithAsset:

Initializes a new player item for a given asset.

+ playerItemWithAsset:

Returns a new player item for a given asset.

- initWithAsset:automaticallyLoadedAssetKeys:

Initializes a player item with the specified asset and the asset keys to be automatically loaded.

+ playerItemWithAsset:automaticallyLoadedAssetKeys:

Creates a player item with the specified asset and the asset keys to be automatically loaded.

Inspecting a Player Item

asset

The asset provided during initialization.

automaticallyLoadedAssetKeys

The array of asset keys to be automatically loaded before the player item is ready to play.

tracks

An array of player item track objects.

status

The status of the player item.

AVPlayerItemStatus

The statuses for a player item.

duration

The duration of the item.

timebase

The timebase information for the item.

loadedTimeRanges

An array of time ranges indicating media data that is readily available.

presentationSize

The size at which the visual portion of the item is presented by the player.

timedMetadata

An array of the most recently encountered timed metadata.

Deprecated
error

The error that caused the player item to fail.

Moving the Playhead

- stepByCount:

Moves the player item’s current time forward or backward by a specified number of steps.

seekableTimeRanges

An array of time ranges within which it is possible to seek.

- seekToTime:completionHandler:

Sets the current playback time to the specified time and executes the specified block when the seek operation completes or is interrupted.

- seekToDate:completionHandler:

Sets the current playback time to the time specified by the date object.

- seekToTime:toleranceBefore:toleranceAfter:completionHandler:

Sets the current playback time within a specified time bound and invokes the specified block when the seek operation completes or is interrupted.

- cancelPendingSeeks

Cancels any pending seek requests and invokes the corresponding completion handlers if present.

- seekToDate:

Sets the current playback time to the time specified by the date object.

Deprecated
- seekToTime:

Sets the current playback time to the specified time.

Deprecated
- seekToTime:toleranceBefore:toleranceAfter:

Sets the current playback time within a specified time bound.

Deprecated

Getting Information About Playback

playbackLikelyToKeepUp

A Boolean value that indicates whether the item will likely play through without stalling.

playbackBufferEmpty

A Boolean value that indicates whether playback has consumed all buffered media and that playback will stall or end.

playbackBufferFull

A Boolean value that indicates whether the internal media buffer is full and that further I/O is suspended.

canPlayReverse

A Boolean value that indicates whether the item can be played in reverse.

canPlayFastForward

A Boolean value that indicates whether the item can be fast forwared.

canPlayFastReverse

A Boolean value that indicates whether the item can be quickly reversed.

canPlaySlowForward

A Boolean value that indicates whether the item can be played slower than normal.

canPlaySlowReverse

A Boolean value that indicates whether the item can be played slowly backward.

canStepBackward

A Boolean value that indicates whether the item supports stepping backward.

canStepForward

A Boolean value that indicates whether the item supports stepping forward.

Getting Timing Information

- currentTime

Returns the current time of the item.

- currentDate

Returns the current time of the item as an NSDate object.

forwardPlaybackEndTime

The time at which forward playback ends.

reversePlaybackEndTime

The time at which reverse playback ends.

Configuring Network Behavior

preferredPeakBitRate

The desired limit, in bits per second, of network bandwidth consumption for this item.

preferredForwardBufferDuration

The duration the player should buffer media from the network ahead of the playhead to guard against playback disruption.

canUseNetworkResourcesForLiveStreamingWhilePaused

A Boolean value that indicates whether the player item can use network resources to keep the playback state up to date while paused.

preferredMaximumResolution

The desired maximum resolution of a video that is to be downloaded.

Configuring an Item's Settings

audioMix

The audio mix parameters to be applied during playback.

videoComposition

The video composition settings to be applied during playback.

customVideoCompositor

The custom video compositor.

AVVideoCompositing

The methods that custom video compositors must implement.

seekingWaitsForVideoCompositionRendering

A Boolean value that indicates whether the item’s timing follows the displayed video frame when seeking with a video composition.

audioTimePitchAlgorithm

The processing algorithm used to manage audio pitch for scaled audio edits.

videoApertureMode

The video aperture mode to apply during playback.

AVVideoApertureMode

A value that describes how a video is scaled or cropped.

Accessing Logs

- accessLog

Returns an object that represents a snapshot of the network access log.

- errorLog

Returns an object that represents a snapshot of the error log.

AVPlayerItemAccessLog

An object used to retrieve the access log associated with a player item.

AVPlayerItemAccessLogEvent

A single entry in a player item's access log.

AVPlayerItemErrorLog

The error log associated with a player item.

AVPlayerItemErrorLogEvent

A single item in a player item's error log.

Managing Authorization

- requestContentAuthorizationAsynchronouslyWithTimeoutInterval:completionHandler:

Presents the user the opportunity to authorize the content for playback.

contentAuthorizationRequestStatus

The status of the most recent content authorization request.

AVContentAuthorizationStatus

A value representing the status of a content authorization request.

authorizationRequiredForPlayback

A Boolean value that indicates whether authorization is required to play the content.

applicationAuthorizedForPlayback

A Boolean value that indicates whether the application can be used to play the content.

contentAuthorizedForPlayback

A Boolean value that indicates whether the content has been authorized by the user.

- cancelContentAuthorizationRequest

Cancels the currently outstanding content authorization request.

Selecting Media Options

currentMediaSelection

The current media selections for each of the receiver's media selection groups.

- selectMediaOption:inMediaSelectionGroup:

Selects a media option in a given media selection group and deselects all other options in that group.

- selectMediaOptionAutomaticallyInMediaSelectionGroup:

Selects the media option in the specified media selection group that best matches the receiver’s automatic selection criteria.

externalSubtitleOptionLanguages

An array of BCP 47 language codes that supplements the list of subtitle options to be presented to the user.

Deprecated
selectedExternalSubtitleOptionLanguage

The BCP 47 language code of the external subtitle option language marked in the user interface.

Deprecated
- selectedMediaOptionInMediaSelectionGroup:

Returns the media selection option that's currently selected from the specified group.

Deprecated

Accessing the Text Style Rules

textStyleRules

An array of text style rules to apply to WebVTT subtitles and other legible text.

Managing the Item’s Outputs

outputs

An array of outputs associated with the player item.

- addOutput:

Adds the specified player item output object to the receiver.

- removeOutput:

Removes the specified player item output object from the receiver.

Managing the Item’s Data Collectors

mediaDataCollectors

The collection of associated media data collectors.

- addMediaDataCollector:

Adds the specified media data collector to the player item’s collection of media collectors.

- removeMediaDataCollector:

Removes the specified media data collector from the player item’s collection of media collectors.

Associating Metadata for Playback with AVKit

navigationMarkerGroups

The time marker groups that provide ways to navigate the player item’s content.

interstitialTimeRanges

The time ranges of the player item’s time line that represent interstitial content.

externalMetadata

An array of additional metadata for the player item to supplement or override that is embedded in the underlying media asset.

nextContentProposal

The item proposed to follow the current content.

Sending Notifications

AVPlayerItemFailedToPlayToEndTimeErrorKey

The key to retrieve an error object from the user info dictionary of an AVPlayerItemTimeJumpedNotification notification.

AVPlayerItemDidPlayToEndTimeNotification

A notification that's posted when the item has played to its end time.

AVPlayerItemFailedToPlayToEndTimeNotification

A notification that's posted when the item failed to play to its end time.

AVPlayerItemTimeJumpedNotification

A notification that's posted when the item’s current time has changed discontinuously.

AVPlayerItemPlaybackStalledNotification

A notification that's posted when posted when some media didn't arrive in time to continue playback.

AVPlayerItemNewAccessLogEntryNotification

A notification that's posted when posted when a new access log entry has been added.

AVPlayerItemNewErrorLogEntryNotification

A notification that's posted when posted when a new error log entry has been added.

Relationships

Inherits From

Conforms To

See Also

Media Playback

AVPlayer

An object that provides the interface to control the player’s transport behavior.

AVQueuePlayer

A player used to play a number of items in sequence.

AVPlayerLayer

An object that manages a player's visual output.

AVPlayerItemMetadataCollector

An object used to capture the date range metadata defined for an HTTP Live Streaming asset.

AVPlayerItemTrack

An object used to modify the presentation state of an asset track being presented by a player.

AVSynchronizedLayer

An object used to synchronize with a specific player item.

AVPlayerMediaSelectionCriteria

An object that specifies the preferred languages and media characteristics for a player.

AVSampleBufferAudioRenderer

An object used to decompress audio and play compressed or uncompressed audio.

AVSampleBufferDisplayLayer

An object that displays compressed or uncompressed video frames.

AVSampleBufferRenderSynchronizer

An object used to synchronize multiple queued sample buffers to a single timeline.

AVRouteDetector

An object that detects the presences of media playback routes.

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software