Class

AVPlayer

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

Declaration

class AVPlayer : NSObject

Overview

An AVPlayer is a controller object used to manage the playback and timing of a media asset. 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.

AVPlayer is for playing a single media asset at a time. You can reuse he player instance to play additional media assets using its replaceCurrentItem(with:) method, but it manages the playback of only a single media asset at a time. The framework also provides a subclass of AVPlayer, called AVQueuePlayer, you use to create and manage the queuing of media assets played sequentially.

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 when making a change on another thread. AVFoundation invokes observeValue(forKeyPath:of:change:context:) on the main thread, even when making the change operation 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, invoke the callback block or closure you supply to these methods to give 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 they are unable to present an asset’s video onscreen. You have two primary approaches you can use to present your video content onscreen:

  • AVKit: The best way to present your video content is with 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: When building a custom interface for your player, use 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—it presents the visual content onscreen. It's 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. Use the synchronized layer 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, or the mini-connector-based HDMI/VGA adapters for full-screen playback at its original fidelity.

In "external screen" mode (also known as mirroring and second display), the host device renders the video data. The host device recompresses and transfers the rendered video 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.

Topics

Creating a Player

init(url: URL)

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

init(playerItem: AVPlayerItem?)

Creates 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: AVPlayer.ActionAtItemEnd

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

enum AVPlayer.ActionAtItemEnd

The actions a player should take when it finishes playing.

func replaceCurrentItem(with: AVPlayerItem?)

Replaces the current player item with a new player item.

var preventsDisplaySleepDuringVideoPlayback: Bool

A Boolean value that indicates whether video playback prevents display and device sleep.

Managing Automatic Waiting Behavior

var automaticallyWaitsToMinimizeStalling: Bool

A Boolean value that indicates whether the player should automatically delay playback in order to minimize stalling.

var reasonForWaitingToPlay: AVPlayer.WaitingReason?

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

struct AVPlayer.WaitingReason

The reasons the player is waiting begin or resume playback.

var timeControlStatus: AVPlayer.TimeControlStatus

A status that indicates whether playback is currently in progress, paused indefinitely, or suspended while waiting for appropriate network conditions.

enum AVPlayer.TimeControlStatus

The player statuses indicating a playback rate change.

func playImmediately(atRate: Float)

Plays the available media data immediately, at the specified rate.

Managing Time

func currentTime() -> CMTime

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 completes or is 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 completes or is interrupted.

Observing Time

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

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

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

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.

Configuring Media Selection Criteria Settings

var appliesMediaSelectionCriteriaAutomatically: Bool

A Boolean value that indicates whether the receiver should apply the current selection criteria automatically to player items.

func mediaSelectionCriteria(forMediaCharacteristic: AVMediaCharacteristic) -> AVPlayerMediaSelectionCriteria?

Returns the automatic selection criteria for media items with the specified media characteristic.

func setMediaSelectionCriteria(AVPlayerMediaSelectionCriteria?, forMediaCharacteristic: AVMediaCharacteristic)

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

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.

var externalPlaybackVideoGravity: AVLayerVideoGravity

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

struct AVLayerVideoGravity

A value that defines how the video is displayed within a layer’s bounds rectangle.

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 time bases.

Managing Audio Output

var isMuted: Bool

A Boolean value that indicates whether the audio output of the player is muted.

var volume: Float

The audio playback volume for the player.

var audioOutputDeviceUniqueID: String?

Specifies the unique ID of the Core Audio output device used to play audio.

Getting Player Properties

var status: AVPlayer.Status

A status that indicates whether the player can be used for playback.

enum AVPlayer.Status

The statuses that indicate whether a player can successfully play items.

var error: Error?

The error that caused the failure.

var currentItem: AVPlayerItem?

The player’s current player item.

var isOutputObscuredDueToInsufficientExternalProtection: Bool

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

Managing Closed Caption Display

var isClosedCaptionDisplayEnabled: Bool

A Boolean value that indicates whether the player uses closed captioning.

Deprecated

Determining HDR Playback

class var availableHDRModes: AVPlayer.HDRMode

The HDR modes that are available for playback.

struct AVPlayer.HDRMode

A bitfield type that specifies an HDR mode.

Setting The GPU

var preferredVideoDecoderGPURegistryID: UInt64

The registry identifier for the GPU used for video decoding.

Relationships

Inherits From

Conforms To

See Also

Media Playback

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 AVPlayerItem

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

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.