Class

AVPlayerItem

AVPlayerItem models the timing and presentation state of an asset played by an AVPlayer object. It provides the interface to seek to various times in the media, determine its presentation size, identify its current time, and much more.

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 init(asset: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 unknown, 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 readyToPlay before it’s ready for use. The following code example illustrates how to register and be notified of status changes:

func prepareToPlay() {
    let url = <#Asset URL#>
    // Create asset to be played
    asset = AVAsset(url: url)
    
    let assetKeys = [
        "playable",
        "hasProtectedContent"
    ]
    // Create a new AVPlayerItem with the asset and an
    // array of asset keys to be automatically loaded
    playerItem = AVPlayerItem(asset: asset,
                              automaticallyLoadedAssetKeys: assetKeys)
    
    // Register as an observer of the player item's status property
    playerItem.addObserver(self,
                           forKeyPath: #keyPath(AVPlayerItem.status),
                           options: [.old, .new],
                           context: &playerItemContext)
    
    // Associate the player item with the player
    player = AVPlayer(playerItem: 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 observeValue(forKeyPath:of:change:context:) method. This method is invoked whenever the status changes giving you the chance to take some action in response (see example).

override func observeValue(forKeyPath keyPath: String?,
                           of object: Any?,
                           change: [NSKeyValueChangeKey : Any]?,
                           context: UnsafeMutableRawPointer?) {
    // Only handle observations for the playerItemContext
    guard context == &playerItemContext else {
        super.observeValue(forKeyPath: keyPath,
                           of: object,
                           change: change,
                           context: context)
        return
    }
    
    if keyPath == #keyPath(AVPlayerItem.status) {
        let status: AVPlayerItemStatus
        
        // Get the status change from the change dictionary
        if let statusNumber = change?[.newKey] as? NSNumber {
            status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
        } else {
            status = .unknown
        }
        
        // Switch over the status
        switch status {
        case .readyToPlay:
        // Player item is ready to play.
        case .failed:
        // Player item failed. See error.
        case .unknown:
            // Player item is not yet ready.
        }
    }
}

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

Symbols

Creating a Player Item

init(url: URL)

Prepares a player item with a given URL.

init(asset: AVAsset)

Initializes a new player item for a given asset.

init(asset: AVAsset, automaticallyLoadedAssetKeys: [String]?)

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

Inspecting a Player Item

var asset: AVAsset

The underlying asset provided during initialization.

var automaticallyLoadedAssetKeys: [String]

The array of asset keys to be automatically loaded before to the player item reaches a status of readyToPlay.

var tracks: [AVPlayerItemTrack]

An array of AVPlayerItemTrack objects.

var status: AVPlayerItemStatus

The status of the player item.

var duration: CMTime

Indicates the duration of the item’s media.

var timebase: CMTimebase?

The timebase information for the item.

var loadedTimeRanges: [NSValue]

The time ranges of the item that have been loaded.

var presentationSize: CGSize

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

var timedMetadata: [AVMetadataItem]?

The timed metadata encountered most recently by the media stream.

var error: Error?

If the player item’s status is failed, this describes the error that caused the failure.

Moving the Playhead

func step(byCount: Int)

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

var seekableTimeRanges: [NSValue]

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

func seek(to: Date)

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

func seek(to: CMTime)

Sets the current playback time to the specified time.

func seek(to: CMTime, completionHandler: (Bool) -> Void)

Sets the current playback time to the specified time and executes the specified block when the seek operation has either been completed or been interrupted.

func seek(to: Date, completionHandler: (Bool) -> Void)

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

func seek(to: CMTime, toleranceBefore: CMTime, toleranceAfter: CMTime)

Sets the current playback time within a specified time bound.

func seek(to: CMTime, toleranceBefore: CMTime, toleranceAfter: CMTime, completionHandler: (Bool) -> Void)

Sets the current playback time within a specified time bound and invokes the specified block when the seek operation has either been completed or been interrupted.

func cancelPendingSeeks()

Cancel any pending seek requests and invoke the corresponding completion handlers if present.

Information About Playback

var isPlaybackLikelyToKeepUp: Bool

Indicates whether the item will likely play through without stalling.

var isPlaybackBufferEmpty: Bool

Indicates whether playback has consumed all buffered media and that playback will stall or end.

var isPlaybackBufferFull: Bool

Indicates whether the internal media buffer is full and that further I/O is suspended.

var canPlayReverse: Bool

A Boolean value indicating whether the item can be played with a rate of -1.0.

var canPlayFastForward: Bool

A Boolean value indicating whether the item can be played at rates greater than 1.0.

var canPlayFastReverse: Bool

A Boolean value indicating whether the item can be played at rates less than –1.0.

var canPlaySlowForward: Bool

A Boolean value indicating whether the item can be played at a rate between 0.0 and 1.0.

var canPlaySlowReverse: Bool

A Boolean value indicating whether the item can be played at a rate between -1.0 and 0.0.

var canStepBackward: Bool

A Boolean value indicating whether the item supports stepping backward.

var canStepForward: Bool

A Boolean value indicating whether the item supports stepping forward.

Timing Information

func currentTime()

Returns the current time of the item.

func currentDate()

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

var forwardPlaybackEndTime: CMTime

The time at which forward playback ends.

var reversePlaybackEndTime: CMTime

The time at which reverse playback ends.

Configuring Network Behavior

var preferredPeakBitRate: Double

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

var preferredForwardBufferDuration: TimeInterval

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

var canUseNetworkResourcesForLiveStreamingWhilePaused: Bool

Indicates whether the player item can use network resources to keep playback state up to date while paused.

Settings

var audioMix: AVAudioMix?

The audio mix parameters to be applied during playback.

var videoComposition: AVVideoComposition?

The video composition settings to be applied during playback.

var seekingWaitsForVideoCompositionRendering: Bool

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

var audioTimePitchAlgorithm: String

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

var customVideoCompositor: AVVideoCompositing?

The custom video compositor, if any.

Accessing Logs

func accessLog()

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

func errorLog()

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

Managing Authorization

func requestContentAuthorizationAsynchronously(withTimeoutInterval: TimeInterval, completionHandler: () -> Void)

Causes appropriate action to be taken to allow the user to authorize the content for playback.

var isAuthorizationRequiredForPlayback: Bool

Indicates whether or not authorization is required to play the content.

var isApplicationAuthorizedForPlayback: Bool

Indicates whether the application can be used to play the content.

var isContentAuthorizedForPlayback: Bool

Indicates whether the content has been authorized by the user (for example, by authorizing the content’s associated account in iTunes).

func cancelContentAuthorizationRequest()

Causes the currently outstanding content authorization request to be cancelled.

Selecting Media Options

var currentMediaSelection: AVMediaSelection

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

func select(AVMediaSelectionOption?, in: AVMediaSelectionGroup)

Selects the media option described by an instance of AVMediaSelectionOption in a given media selection group and deselects all other options in that group.

func selectedMediaOption(in: AVMediaSelectionGroup)

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

func selectMediaOptionAutomatically(in: AVMediaSelectionGroup)

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

Accessing the Text Style Rules

var textStyleRules: [AVTextStyleRule]?

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

Managing the Item’s Outputs

var outputs: [AVPlayerItemOutput]

The outputs associated with the item.

func add(AVPlayerItemOutput)

Adds the specified player item output object to the receiver.

func remove(AVPlayerItemOutput)

Removes the specified player item output object from the receiver.

Managing the Item’s Data Collectors

var mediaDataCollectors: [AVPlayerItemMediaDataCollector]

The collection of associated media data collectors.

func add(AVPlayerItemMediaDataCollector)

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

func remove(AVPlayerItemMediaDataCollector)

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

Associating Metadata for Playback with AVKit

var navigationMarkerGroups: [AVNavigationMarkersGroup]

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

var interstitialTimeRanges: [AVInterstitialTimeRange]

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

var externalMetadata: [AVMetadataItem]

Additional metadata for the player item to supplement or override that embedded in the underlying media asset.

var nextContentProposal: AVContentProposal?

The item proposed to follow the current content.

Constants

AVPlayerItemStatus

Constants that represent the status of an item

Notification Key

Key to retrieve information from a notification’s user info dictionary.

Notifications

static let AVPlayerItemDidPlayToEndTime: NSNotification.Name

Posted when the item has played to its end time.

static let AVPlayerItemFailedToPlayToEndTime: NSNotification.Name

Posted when the item failed to play to its end time.

static let AVPlayerItemTimeJumped: NSNotification.Name

Posted when the item’s current time has changed discontinuously.

static let AVPlayerItemPlaybackStalled: NSNotification.Name

Posted when some media did not arrive in time to continue playback.

static let AVPlayerItemNewAccessLogEntry: NSNotification.Name

Posted when a new access log entry has been added.

static let AVPlayerItemNewErrorLogEntry: NSNotification.Name

Posted when a new error log entry has been added.

Relationships

Inherits From