Class

AVPlayer​Item

AVPlayer​Item 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 AVPlayer​Item 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 AVAsynchronous​Key​Value​Loading protocol to load the values you need. Alternatively, AVPlayer​Item can automatically load the needed asset data for you by passing the desired set of keys to its init(asset:​automatically​Loaded​Asset​Keys:​) initializer. When the player item is ready to play, those asset properties will have been loaded and are ready for use.

AVPlayer​Item 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 ready​To​Play 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 prepare​To​Play method registers to observe the player item’s status property using the add​Observer(_:​for​Key​Path:​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 observe​Value(for​Key​Path:​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 ready​To​Play, 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, automatically​Loaded​Asset​Keys:​ [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 automatically​Loaded​Asset​Keys:​ [String]

The array of asset keys to be automatically loaded before to the player item reaches a status of ready​To​Play.

var tracks:​ [AVPlayer​Item​Track]

An array of AVPlayer​Item​Track objects.

var status:​ AVPlayer​Item​Status

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 loaded​Time​Ranges:​ [NSValue]

The time ranges of the item that have been loaded.

var presentation​Size:​ CGSize

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

var timed​Metadata:​ [AVMetadata​Item]?

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(by​Count:​ Int)

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

var seekable​Time​Ranges:​ [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, completion​Handler:​ (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, completion​Handler:​ (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, tolerance​Before:​ CMTime, tolerance​After:​ CMTime)

Sets the current playback time within a specified time bound.

func seek(to:​ CMTime, tolerance​Before:​ CMTime, tolerance​After:​ CMTime, completion​Handler:​ (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 cancel​Pending​Seeks()

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

Information About Playback

var is​Playback​Likely​To​Keep​Up:​ Bool

Indicates whether the item will likely play through without stalling.

var is​Playback​Buffer​Empty:​ Bool

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

var is​Playback​Buffer​Full:​ Bool

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

var can​Play​Reverse:​ Bool

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

var can​Play​Fast​Forward:​ Bool

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

var can​Play​Fast​Reverse:​ Bool

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

var can​Play​Slow​Forward:​ Bool

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

var can​Play​Slow​Reverse:​ Bool

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

var can​Step​Backward:​ Bool

A Boolean value indicating whether the item supports stepping backward.

var can​Step​Forward:​ Bool

A Boolean value indicating whether the item supports stepping forward.

Timing Information

func current​Time()

Returns the current time of the item.

func current​Date()

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

var forward​Playback​End​Time:​ CMTime

The time at which forward playback ends.

var reverse​Playback​End​Time:​ CMTime

The time at which reverse playback ends.

Configuring Network Behavior

var preferred​Peak​Bit​Rate:​ Double

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

var preferred​Forward​Buffer​Duration:​ Time​Interval

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

var can​Use​Network​Resources​For​Live​Streaming​While​Paused:​ Bool

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

Settings

var audio​Mix:​ AVAudio​Mix?

The audio mix parameters to be applied during playback.

var video​Composition:​ AVVideo​Composition?

The video composition settings to be applied during playback.

var seeking​Waits​For​Video​Composition​Rendering:​ Bool

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

var audio​Time​Pitch​Algorithm:​ String

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

Accessing Logs

func access​Log()

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

func error​Log()

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

Managing Authorization

func request​Content​Authorization​Asynchronously(with​Timeout​Interval:​ Time​Interval, completion​Handler:​ () -> Void)

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

var is​Authorization​Required​For​Playback:​ Bool

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

var is​Application​Authorized​For​Playback:​ Bool

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

var is​Content​Authorized​For​Playback:​ Bool

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

func cancel​Content​Authorization​Request()

Causes the currently outstanding content authorization request to be cancelled.

Selecting Media Options

var current​Media​Selection:​ AVMedia​Selection

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

func select(AVMedia​Selection​Option?, in:​ AVMedia​Selection​Group)

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

func selected​Media​Option(in:​ AVMedia​Selection​Group)

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

func select​Media​Option​Automatically(in:​ AVMedia​Selection​Group)

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 text​Style​Rules:​ [AVText​Style​Rule]?

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

Managing the Item’s Outputs

var outputs:​ [AVPlayer​Item​Output]

The outputs associated with the item.

func add(AVPlayer​Item​Output)

Adds the specified player item output object to the receiver.

func remove(AVPlayer​Item​Output)

Removes the specified player item output object from the receiver.

Managing the Item’s Data Collectors

func add(AVPlayer​Item​Media​Data​Collector)

Adds the specified media data collector to the player item’s collection of media​Data​Collectors.

func remove(AVPlayer​Item​Media​Data​Collector)

Removes the specified media data collector from the player item’s collection of media​Data​Collectors.

Associating Metadata for Playback with AVKit

var navigation​Marker​Groups:​ [AVNavigation​Markers​Group]

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

var interstitial​Time​Ranges:​ [AVInterstitial​Time​Range]

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

var external​Metadata:​ [AVMetadata​Item]

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

var next​Content​Proposal:​ AVContent​Proposal?

The item proposed to follow the current content.

Constants

AVPlayer​Item​Status

Constants that represent the status of an item

Notification Key

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

Notifications

static let AVPlayer​Item​Time​Jumped:​ NSNotification.Name

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

static let AVPlayer​Item​Playback​Stalled:​ NSNotification.Name

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

Relationships

Inherits From