Class

AVPlayerItem

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

Declaration

class 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 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 AVPlayerItem.Status.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 AVPlayerItem.Status.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 AVPlayerItem.Status.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 AVPlayerItem.Status.failed. You can get the NSError providing the details of the failure by querying the player item’s error property.

Topics

Creating a Player Item

init(url: URL)

Initializes 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 asset provided during initialization.

var automaticallyLoadedAssetKeys: [String]

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

var tracks: [AVPlayerItemTrack]

An array of player item track objects.

var status: AVPlayerItem.Status

The status of the player item.

enum AVPlayerItem.Status

The statuses for a player item.

var duration: CMTime

The duration of the item.

var timebase: CMTimebase?

The timebase information for the item.

var loadedTimeRanges: [NSValue]

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

var presentationSize: CGSize

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

var timedMetadata: [AVMetadataItem]?

An array of the most recently encountered timed metadata.

var error: Error?

The error that caused the player item to fail.

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: CMTime, completionHandler: ((Bool) -> Void)? = nil)

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: Date, completionHandler: ((Bool) -> Void)? = nil) -> Bool

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

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

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

func cancelPendingSeeks()

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

func seek(to: Date) -> Bool

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

Deprecated
func seek(to: CMTime)

Sets the current playback time to the specified time.

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

Sets the current playback time within a specified time bound.

Deprecated

Getting Information About Playback

var isPlaybackLikelyToKeepUp: Bool

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

var isPlaybackBufferEmpty: Bool

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

var isPlaybackBufferFull: Bool

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

var canPlayReverse: Bool

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

var canPlayFastForward: Bool

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

var canPlayFastReverse: Bool

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

var canPlaySlowForward: Bool

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

var canPlaySlowReverse: Bool

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

var canStepBackward: Bool

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

var canStepForward: Bool

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

Getting Timing Information

func currentTime() -> CMTime

Returns the current time of the item.

func currentDate() -> Date?

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

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

var canUseNetworkResourcesForLiveStreamingWhilePaused: Bool

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

var preferredMaximumResolution: CGSize

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

Configuring an Item's 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.

protocol AVVideoCompositing

The methods that custom video compositors must implement.

var seekingWaitsForVideoCompositionRendering: Bool

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

var audioTimePitchAlgorithm: AVAudioTimePitchAlgorithm

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

var videoApertureMode: AVVideoApertureMode

The video aperture mode to apply during playback.

struct AVVideoApertureMode

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

Accessing Logs

func accessLog() -> AVPlayerItemAccessLog?

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

func errorLog() -> AVPlayerItemErrorLog?

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

class AVPlayerItemAccessLog

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

class AVPlayerItemAccessLogEvent

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

class AVPlayerItemErrorLog

The error log associated with a player item.

class AVPlayerItemErrorLogEvent

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

Managing Authorization

var contentAuthorizationRequestStatus: AVContentAuthorizationStatus

The status of the most recent content authorization request.

enum AVContentAuthorizationStatus

A value representing the status of a content authorization request.

var isAuthorizationRequiredForPlayback: Bool

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

var isApplicationAuthorizedForPlayback: Bool

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

var isContentAuthorizedForPlayback: Bool

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

func cancelContentAuthorizationRequest()

Cancels the currently outstanding content authorization request.

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 a media option in a given media selection group and deselects all other options in that group.

func selectMediaOptionAutomatically(in: AVMediaSelectionGroup)

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

func selectedMediaOption(in: AVMediaSelectionGroup) -> AVMediaSelectionOption?

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

Deprecated

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]

An array of outputs associated with the player 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 media collectors.

func remove(AVPlayerItemMediaDataCollector)

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

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 time line that represent interstitial content.

var externalMetadata: [AVMetadataItem]

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

var nextContentProposal: AVContentProposal?

The item proposed to follow the current content.

Sending Notifications

let AVPlayerItemFailedToPlayToEndTimeErrorKey: String

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

static let AVPlayerItemDidPlayToEndTime: NSNotification.Name

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

static let AVPlayerItemFailedToPlayToEndTime: NSNotification.Name

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

static let AVPlayerItemTimeJumped: NSNotification.Name

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

static let AVPlayerItemPlaybackStalled: NSNotification.Name

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

static let AVPlayerItemNewAccessLogEntry: NSNotification.Name

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

static let AVPlayerItemNewErrorLogEntry: NSNotification.Name

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

Relationships

Inherits From

See Also

Media Playback

class AVPlayer

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

class AVQueuePlayer

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

class AVPlayerLayer

An object that manages a player's visual output.

class AVPlayerItemMetadataCollector

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

class AVPlayerItemTrack

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

class AVSynchronizedLayer

An object used to synchronize with a specific player item.

class AVPlayerMediaSelectionCriteria

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

class AVSampleBufferAudioRenderer

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

class AVSampleBufferDisplayLayer

An object that displays compressed or uncompressed video frames.

class AVSampleBufferRenderSynchronizer

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

class AVRouteDetector

An object that detects the presences of media playback routes.