Class

AVPlayer

An AVPlayer is a controller object used to manage the playback and timing of a media asset. It provides the interface to control the player’s transport behavior such as its ability to play, pause, change the playback rate, and seek to various points in time within the media’s timeline. You can use an AVPlayer to play local and remote file-based media, such as QuickTime movies and MP3 audio files, as well as audiovisual media served using HTTP Live Streaming.

Overview

You use an AVPlayer to play media assets, which AVFoundation models using the AVAsset class. AVAsset only models the static aspects of the media, such as its duration or creation date, and on its own, is unsuitable for playback with an AVPlayer. To play an asset, you need to create an instance of its dynamic counterpart found in AVPlayerItem. This object models the timing and presentation state of an asset played by an instance of AVPlayer. See the AVPlayerItem reference for more details.

AVPlayer is a dynamic object whose state continuously changes. There are two approaches you can use to observe a player’s state:

  • General State Observations: You can use Key-value observing (KVO) to observe state changes to many of the player’s dynamic properties, such as its currentItem or its playback rate. You should register and unregister for KVO change notifications on the main thread. This avoids the possibility of receiving a partial notification if a change is being made on another thread. AV Foundation invokes observeValue(forKeyPath:of:change:context:) on the main thread, even if the change operation is made on another thread.

  • Timed State Observations: KVO works well for general state observations, but isn’t intended for observing continuously changing state like the player’s time. AVPlayer provides two methods to observe time changes:

    These methods let you observe time changes either periodically or by boundary, respectively. As changes occur, the callback block or closure you supply to these methods is invoked giving you the opportunity to take some action such as updating the state of your player’s user interface.

AVPlayer and AVPlayerItem are nonvisual objects meaning that on their own are unable to present an asset’s video on screen. You have two primary approaches you can use to present your video content on screen:

  • AVKit: The best way to present your video content is by using the AVKit framework’s AVPlayerViewController class in iOS and tvOS or the AVPlayerView class in macOS. These classes present the video content, along with playback controls and other media features giving you a full-featured playback experience.

  • AVPlayerLayer: If you are building a custom interface for your player, you use a Core Animation CALayer subclass provided by AVFoundation called AVPlayerLayer. The player layer can be set as a view’s backing layer or can be added directly to the layer hierarchy. Unlike AVPlayerView and AVPlayerViewController, a player layer doesn’t present any playback controls, but simply presents the visual content on screen. It is up to you to build the playback transport controls to play, pause, and seek through the media.

Alongside the visual content presented with AVKit or AVPlayerLayer, you can also present animated content synchronized with the player’s timing using AVSynchronizedLayer. This is a special Core Animation CALayer subclass, that is used to confer the current player timing onto its layer subtree. You can use AVSynchronizedLayer to build custom effects in Core Animation, such as animated lower thirds or video transitions, and have them play in sync with the timing of the player’s current AVPlayerItem.

External Playback Mode

External playback mode is when video data is sent to an external device such as Apple TV via AirPlay and the mini-connector-based HDMI/VGA adapters for full screen playback at its original fidelity. AirPlay Video playback is also considered as an "external playback" mode.

In "external screen" mode (also known as mirroring and second display), video data is rendered on the host device (e.g. iPhone), rendered video is recompressed and transferred to the external device, and the external device decompresses and displays the video.

External playback properties affect AirPlay Video playback and are the replacement for the deprecated AirPlay support properties.

Symbols

Creating a Player

init(url: URL)

Initializes a new player to play a single audiovisual resource referenced by a given URL.

init(playerItem: AVPlayerItem?)

Initializes a new player to play the specified player item.

Managing Playback

func play()

Begins playback of the current item.

func pause()

Pauses playback of the current item.

var rate: Float

The current playback rate.

var actionAtItemEnd: AVPlayerActionAtItemEnd

The action to perform when the current player item has finished playing.

func replaceCurrentItem(with: AVPlayerItem?)

Replaces the current player item with a new player item.

Managing Automatic Waiting Behavior

var automaticallyWaitsToMinimizeStalling: Bool

Indicates if the player should automatically delay playback in order to minimize stalling.

var reasonForWaitingToPlay: String?

Indicates the reason the player is currently waiting for playback to begin or resume.

var timeControlStatus: AVPlayerTimeControlStatus

Indicates whether playback is currently in progress, paused indefinitely, or suspended while waiting for appropriate network conditions.

func playImmediately(atRate: Float)

Immediately plays the available media data at the specified rate.

Managing Time

func currentTime()

Returns the current time of the current player item.

func seek(to: CMTime)

Sets the current playback time to the specified time.

func seek(to: Date)

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

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.

Observing Time

func addPeriodicTimeObserver(forInterval: CMTime, queue: DispatchQueue?, using: (CMTime) -> Void)

Requests the periodic invocation of a given block during playback to report changing time.

func addBoundaryTimeObserver(forTimes: [NSValue], queue: DispatchQueue?, using: () -> Void)

Requests the invocation of a block when specified times are traversed during normal playback.

func removeTimeObserver(Any)

Cancels a previously registered periodic or boundary time observer.

Media Selection Criteria Settings

var appliesMediaSelectionCriteriaAutomatically: Bool

Indicates whether the receiver should apply the current selection criteria automatically to player items.

func mediaSelectionCriteria(forMediaCharacteristic: String)

Returns the automatic selection criteria for media that has the specified media characteristic.

func setMediaSelectionCriteria(AVPlayerMediaSelectionCriteria?, forMediaCharacteristic: String)

Applies automatic selection criteria for media that has the specified media characteristic.

Managing Closed Caption Display

var isClosedCaptionDisplayEnabled: Bool

Indicates whether the player uses closed captioning.

Managing External Playback

var allowsExternalPlayback: Bool

A Boolean value that indicates whether the player allows switching to external playback mode.

var isExternalPlaybackActive: Bool

A Boolean value that indicates whether the player is currently playing video in external playback mode.

var usesExternalPlaybackWhileExternalScreenIsActive: Bool

A Boolean value that indicates whether the player should automatically switch to external playback mode while the external screen mode is active in order to play video content.

var externalPlaybackVideoGravity: String

The video gravity of the player for external playback mode only.

Synchronizing Playback to an External Source

The advanced synchronization and rate control methods in this section are currently only supported for file-based media and are not supported for media served using HTTP Live Streaming.

func setRate(Float, time: CMTime, atHostTime: CMTime)

Synchronizes the playback rate and time of the current item with an external source.

func preroll(atRate: Float, completionHandler: (Bool) -> Void)? = nil)

Begins loading media data to prime the media pipelines for playback.

func cancelPendingPrerolls()

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

var masterClock: CMClock?

The master clock used for item timebases.

Managing Audio Output

var isMuted: Bool

Indicates whether the audio output of the player is muted.

var volume: Float

The audio playback volume for the player, ranging from 0.0 through 1.0 on a linear scale.

Player Properties

var status: AVPlayerStatus

Indicates whether the player can be used for playback.

var error: Error?

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

var currentItem: AVPlayerItem?

The player’s current player item.

var isOutputObscuredDueToInsufficientExternalProtection: Bool

A Boolean value indicating whether output is being obscured because of insufficient external protection.

Constants

AVPlayerStatus

Possible values of the status property, to indicate whether it can successfully play items.

AVPlayerActionAtItemEnd

You use these constants with actionAtItemEnd to indicate the action a player should take when it finishes playing.

AVPlayerTimeControlStatus

These constants are the allowable values of the player’s timeControlStatus property.

Reason for Waiting Constants

The following are valid constant values for the player’s reasonForWaitingToPlay property.

Relationships

Inherits From

Conforms To