AVPlayer Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/AVFoundation.framework
Availability
Available in iOS 4.0 and later.
Companion guide
Declared in
AVPlayer.h
Related sample code

Overview

You use an AVPlayer object to implement controllers and user interfaces for single- or multiple-item playback. The multiple-item case supports advanced behaviors.

AVPlayer works equally well with local and remote media files, providing you with appropriate information about readiness to play or about the need to await additional data before continuing.

You can display the visual content of items played by an instance of AVPlayer in a CoreAnimation layer of class AVPlayerLayer; to synchronize real-time playback with other CoreAnimation layers, you can use AVSynchronizedLayer. You cannot use an instance of AVVideoCompositionCoreAnimationTool with an AVPlayer object; for offline rendering you should instead use AVAssetExportSession.

You can observe the status of a player using key-value observing. So that you can add and remove observers safely, AVPlayer serializes notifications of changes that occur dynamically during playback on a dispatch queue. By default, this queue is the main queue (see dispatch_get_main_queue). To ensure safe access to a player’s nonatomic properties while dynamic changes in playback state may be reported, you must serialize access with the receiver’s notification queue. In the common case, such serialization is naturally achieved by invoking AVPlayer’s various methods on the main thread or queue.

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.

Tasks

Creating a Player

Managing Playback

Managing Time

Managing External Playback

Synchronizing Playback to an External Source

Timed Observations

Managing Closed Caption Display

Managing Audio Output

Player Properties

Managing AirPlay

Media Selection Criteria Settings

Properties

actionAtItemEnd

The action to perform when an item has finished playing.

@property(nonatomic) AVPlayerActionAtItemEnd actionAtItemEnd
Discussion

For possible values, see “AVPlayerActionAtItemEnd.”

Availability
  • Available in iOS 4.0 and later.
Declared In
AVPlayer.h

allowsExternalPlayback

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

@property(nonatomic) BOOL allowsExternalPlayback
Discussion

The default value of this property is YES.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVPlayer.h

appliesMediaSelectionCriteriaAutomatically

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

@property(nonatomic) BOOL appliesMediaSelectionCriteriaAutomatically
Discussion

By default, the AVPlayer instance applies selection criteria based on system preferences. To override the default criteria for any media selection group, use setMediaSelectionCriteria:forMediaCharacteristic:.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVPlayer.h

closedCaptionDisplayEnabled

Indicates whether the player uses closed captioning.

@property(nonatomic, getter=isClosedCaptionDisplayEnabled) BOOL closedCaptionDisplayEnabled
Availability
  • Available in iOS 4.0 and later.
Declared In
AVPlayer.h

currentItem

The player’s current item. (read-only)

@property(nonatomic, readonly) AVPlayerItem *currentItem
Availability
  • Available in iOS 4.0 and later.
Declared In
AVPlayer.h

error

If the receiver’s status is AVPlayerStatusFailed, this describes the error that caused the failure. (read-only)

@property(nonatomic, readonly) NSError *error
Discussion

The value of this property is an error object that describes what caused the receiver to no longer be able to play items. If the receiver's status is not AVPlayerStatusFailed, the value of this property is nil.

Availability
  • Available in iOS 4.0 and later.
See Also
Declared In
AVPlayer.h

externalPlaybackActive

A Boolean value that indicates whether the player is currently playing video in external playback mode. (read-only)

@property(nonatomic, readonly, getter=isExternalPlaybackActive) BOOL externalPlaybackActive
Availability
  • Available in iOS 6.0 and later.
Declared In
AVPlayer.h

externalPlaybackVideoGravity

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

@property(nonatomic, copy) NSString *externalPlaybackVideoGravity
Availability
  • Available in iOS 6.0 and later.
Declared In
AVPlayer.h

masterClock

The master clock used for item timebases.

@property(nonatomic, retain) CMClockRef masterClock
Discussion

The default value of this property is NULL, which means that the master clock is automatically chosen. When non-NULL, this property overrides the automatic choice of master clock for item timebases. This is most useful when you are synchronizing video-only movies with audio played by another source.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVPlayer.h

muted

Indicates whether the audio output of the player is muted.

@property(nonatomic, getter=isMuted) BOOL muted
Availability
  • Available in iOS 7.0 and later.
Declared In
AVPlayer.h

outputObscuredDueToInsufficientExternalProtection

A Boolean value indicating whether output is being obscured because of insufficient external protection. (read-only)

@property(nonatomic, readonly) BOOL outputObscuredDueToInsufficientExternalProtection
Discussion

Items that incorporate copy protection or other forms of security might have their visual content obscured by the player object if the current device configuration does not meet the requirements for protecting the item. This property reports whether the player is currently obscuring the item. If the current item does not require external protection or if the device configuration sufficiently protects the item, the value of this property is set to NO.

You can use this property to determine whether to change your app’s user interface to reflect the change in visibility. You can observe changes to the value of this property using Key-value observing.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVPlayer.h

rate

The current rate of playback.

@property(nonatomic) float rate
Discussion

A value of 0.0 means pauses the video, while a value of 1.0 play at the natural rate of the current item. Rates other than 0.0 and 1.0 can be used if the associated player item returns YES for the AVPlayerItem properties canPlaySlowForward or canPlayFastForward. Negative rate value ranges are supported if the player item returns YES for the canPlayReverse, canPlaySlowReverse, and canPlayFastReverse properties.

Availability
  • Available in iOS 4.0 and later.
See Also
Declared In
AVPlayer.h

status

Indicates whether the player can be used for playback. (read-only)

@property(nonatomic, readonly) AVPlayerStatus status
Discussion

When the value of this property is AVPlayerStatusFailed, you can no longer use the player for playback and you need to create a new instance to replace it. If this happens, you can check the value of the error property to determine the nature of the failure.

This property is key value observable using Key-value observing.

Availability
  • Available in iOS 4.0 and later.
See Also
Declared In
AVPlayer.h

usesExternalPlaybackWhileExternalScreenIsActive

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.

@property(nonatomic) BOOL usesExternalPlaybackWhileExternalScreenIsActive
Discussion

The player will automatically switch back to the external screen mode once video playback concludes. A brief transition may be visible on the external display when automatically switching between the two modes. The default value of this property is NO. The value of this property has no effect if allowsExternalPlayback is NO.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVPlayer.h

volume

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

@property(nonatomic) float volume
Discussion

A value of 0.0 indicates silence; a value of 1.0 (the default) indicates full audio volume for the player instance.

Use this property to control a player’s audio volume relative to other audio output.

To provide UI in iOS for adjusting system audio playback volume, use the MPVolumeView class, which provides media playback controls that iOS users expect and whose appearance you can customize.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVPlayer.h

Class Methods

playerWithPlayerItem:

Returns a new player initialized to play a given single audiovisual item

+ (id)playerWithPlayerItem:(AVPlayerItem *)item
Parameters
item

A player item.

Return Value

A new player, initialized to play item.

Discussion

You can use this method to play items for which an AVAsset object has previously been created (see initWithAsset: in AVPlayerItem).

Availability
  • Available in iOS 4.0 and later.
Declared In
AVPlayer.h

playerWithURL:

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

+ (id)playerWithURL:(NSURL *)URL
Parameters
URL

An URL that identifies an audiovisual resource.

Return Value

A new player initialized to play the audiovisual resource specified by URL.

Discussion

This method implicitly creates an AVPlayerItem object. You can get the player item using currentItem.

Availability
  • Available in iOS 4.0 and later.
Declared In
AVPlayer.h

Instance Methods

addBoundaryTimeObserverForTimes:queue:usingBlock:

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

- (id)addBoundaryTimeObserverForTimes:(NSArray *)times queue:(dispatch_queue_t)queue usingBlock:(void (^)(void))block
Parameters
times

An array of NSValue objects containing CMTime values representing the times at which to invoke block.

queue

A serial queue onto which block should be enqueued.

If you pass NULL, the main queue (obtained using dispatch_get_main_queue(3) Mac OS X Developer Tools Manual Page) is used. Passing a concurrent queue will result in undefined behavior.

block

The block to be invoked when any of the times in times is crossed during normal playback.

Return Value

An opaque object that you pass as the argument to removeTimeObserver: to stop observation.

Discussion

You must retain the returned value as long as you want the time observer to be invoked by the player. Each invocation of this method should be paired with a corresponding call to removeTimeObserver:.

Special Considerations

The thread block is invoked on may not be serviced by an application run loop. If you need to perform an operation in the user interface, you must ensure that the work is bounced to the main thread.

Availability
  • Available in iOS 4.0 and later.
Declared In
AVPlayer.h

addPeriodicTimeObserverForInterval:queue:usingBlock:

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

- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block
Parameters
interval

The interval of invocation of the block during normal playback, according to progress of the current time of the player.

queue

A serial queue onto which block should be enqueued.

If you pass NULL, the main queue (obtained using dispatch_get_main_queue(3) Mac OS X Developer Tools Manual Page) is used. Passing a concurrent queue will result in undefined behavior.

block

The block to be invoked periodically.

The block takes a single parameter:

time

The time at which the block is invoked.

Return Value

An opaque object that you pass as the argument to removeTimeObserver: to cancel observation.

Discussion

You must retain the returned value as long as you want the time observer to be invoked by the player. Each invocation of this method should be paired with a corresponding call to removeTimeObserver:.

The block is invoked periodically at the interval specified, interpreted according to the timeline of the current item. The block is also invoked whenever time jumps and whenever playback starts or stops. If the interval corresponds to a very short interval in real time, the player may invoke the block less frequently than requested. Even so, the player will invoke the block sufficiently often for the client to update indications of the current time appropriately in its end-user interface.

Special Considerations

Releasing the observer object without invoking removeTimeObserver: will result in undefined behavior.

Availability
  • Available in iOS 4.0 and later.
Related Sample Code
Declared In
AVPlayer.h

cancelPendingPrerolls

Cancels the preloading of media data.

- (void)cancelPendingPrerolls
Discussion

This method cancels any pending operations to prepare the render pipeline for the current item.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVPlayer.h

currentTime

Returns the current time of the current item.

- (CMTime)currentTime
Return Value

The current time of the current item.

Discussion

This property is not key-value observable; use addPeriodicTimeObserverForInterval:queue:usingBlock: or addBoundaryTimeObserverForTimes:queue:usingBlock: instead.

Availability
  • Available in iOS 4.0 and later.
Declared In
AVPlayer.h

initWithPlayerItem:

Initializes a new player to play a given single audiovisual item.

- (id)initWithPlayerItem:(AVPlayerItem *)item
Parameters
item

A player item.

Return Value

The receiver, initialized to play item.

Discussion

You can use this method to play items for which you have an existing AVAsset object (see initWithAsset: in AVPlayerItem).

Availability
  • Available in iOS 4.0 and later.
Declared In
AVPlayer.h

initWithURL:

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

- (id)initWithURL:(NSURL *)URL
Parameters
URL

An URL that identifies an audiovisual resource.

Return Value

The receiver, initialized to play the audiovisual resource specified by URL.

Discussion

This method implicitly creates an AVPlayerItem object. You can get the player item using currentItem.

Availability
  • Available in iOS 4.0 and later.
Declared In
AVPlayer.h

mediaSelectionCriteriaForMediaCharacteristic:

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

- (AVPlayerMediaSelectionCriteria *)mediaSelectionCriteriaForMediaCharacteristic:(NSString *)mediaCharacteristic
Parameters
mediaCharacteristic

The media characteristic for which the selection criteria is to be returned. Supported values include AVMediaCharacteristicAudible, AVMediaCharacteristicLegible, and AVMediaCharacteristicVisual.

Return Value

The automatic media selection criteria for mediaCharacteristic.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVPlayer.h

pause

Pauses playback.

- (void)pause
Discussion

This is the same as setting rate to 0.0.

Availability
  • Available in iOS 4.0 and later.
See Also
Declared In
AVPlayer.h

play

Begins playback of the current item.

- (void)play
Discussion

This is the same as setting rate to 1.0.

Availability
  • Available in iOS 4.0 and later.
See Also
Declared In
AVPlayer.h

prerollAtRate:completionHandler:

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

- (void)prerollAtRate:(float)rate completionHandler:(void (^)(BOOL finished))completionHandler
Parameters
rate

The playback rate to use when determining how much data to load.

completionHandler

A block to execute when the player finishes the load attempt. This block takes a single Boolean parameter that contains YES if the data was loaded or NO if there was a problem. For example, the value might be NO if the preroll was interrupted by a time change or incompatible rate change.

Discussion

This method loads data starting at the item’s current playback time. The current rate for the playback item should always be 0 prior to calling this method. After the method calls the completion handler, you can change the item’s playback rate to begin playback.

If the player object is not ready to play (its status property is not AVPlayerStatusReadyToPlay), this method throws an exception.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVPlayer.h

removeTimeObserver:

Cancels a previously registered time observer.

- (void)removeTimeObserver:(id)observer
Discussion

Upon return, the caller is guaranteed that no new time observer blocks will begin executing. Depending on the calling thread and the queue used to add the time observer, an in-flight block may continue to execute after this method returns. You can guarantee synchronous time observer removal by enqueuing the call to removeTimeObserver on that queue. Alternatively, call dispatch_sync(queue, ^{}) after removeTimeObserver to wait for any in-flight blocks to finish executing.

You should use this method to explicitly cancel each time observer added using addPeriodicTimeObserverForInterval:queue:usingBlock: and addBoundaryTimeObserverForTimes:queue:usingBlock:.

Availability
  • Available in iOS 4.0 and later.
Declared In
AVPlayer.h

replaceCurrentItemWithPlayerItem:

Replaces the player item with a new player item.

- (void)replaceCurrentItemWithPlayerItem:(AVPlayerItem *)item
Parameters
item

A player item.

Discussion

You can only use this method with players created without queues. If the player was not initialized with a single item and no queue, the method throws an exception.

The item replacement occurs asynchronously; observe the currentItem property to find out when the replacement will/did occur.

Special Considerations

The new item must have the same compositor as the item it replaces, or have no compositor.

Availability
  • Available in iOS 4.0 and later.
Related Sample Code
Declared In
AVPlayer.h

seekToDate:

Moves the playback cursor to the time specified by a date object.

- (void)seekToDate:(NSDate *)date
Parameters
date

The time at which to move the playback cursor.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVPlayer.h

seekToDate:completionHandler:

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

- (void)seekToDate:(NSDate *)date completionHandler:(void (^)(BOOL finished))completionHandler
Parameters
date

The time to which to move the playback cursor.

completionHandler

The block to invoke when the seek operation has either been completed or been interrupted. The block takes one argument:

finished

Indicates whether the seek operation completed.

Discussion

Use this method to seek to a specified time for the current player item and be notified when the operation completes. If the seek request completes without being interrupted (either by another seek request or by any other operation), the completion handler you provide is executed with the finished parameter set to YES.

If another seek request is already in progress when you call this method, the completion handler for the in-progress seek request is executed immediately with the finished parameter set to NO.

Availability
  • Available in iOS 5.0 and later.
Declared In
AVPlayer.h

seekToTime:

Moves the playback cursor to a given time.

- (void)seekToTime:(CMTime)time
Parameters
time

The time to which to move the playback cursor.

Discussion

The time seeked to may differ from the specified time for efficiency. For sample accurate seeking see seekToTime:toleranceBefore:toleranceAfter:.

Availability
  • Available in iOS 4.0 and later.
Related Sample Code
Declared In
AVPlayer.h

seekToTime:completionHandler:

Moves the playback cursor and executes the specified block when the seek operation has either been completed or been interrupted.

- (void)seekToTime:(CMTime)time completionHandler:(void (^)(BOOL finished))completionHandler
Parameters
time

The time to which you would like to move the playback cursor.

completionHandler

The block to invoke when the seek operation has either been completed or been interrupted. The block takes one argument:

finished

Indicates whether the seek operation completed.

Discussion

Use this method to seek to a specified time for the current player item and be notified when the operation completes. If the seek request completes without being interrupted (either by another seek request or by any other operation), the completion handler you provide is executed with the finished parameter set to YES.

If another seek request is already in progress when you call this method, the completion handler for the in-progress seek request is executed immediately with the finished parameter set to NO.

Availability
  • Available in iOS 5.0 and later.
Declared In
AVPlayer.h

seekToTime:toleranceBefore:toleranceAfter:

Moves the playback cursor within a specified time bound.

- (void)seekToTime:(CMTime)time toleranceBefore:(CMTime)toleranceBefore toleranceAfter:(CMTime)toleranceAfter
Parameters
time

The time to which you would like to move the playback cursor.

toleranceBefore

The tolerance allowed before time.

toleranceAfter

The tolerance allowed after time.

Discussion

The time seeked to will be within the range [time-beforeTolerance, time+afterTolerance], and may differ from the specified time for efficiency. If you pass kCMTimeZero for both toleranceBefore and toleranceAfter (to request sample accurate seeking), you may incur additional decoding delay.

Passing kCMTimePositiveInfinity for both toleranceBefore and toleranceAfter is the same as messaging seekToTime: directly.

Availability
  • Available in iOS 4.0 and later.
Declared In
AVPlayer.h

seekToTime:toleranceBefore:toleranceAfter:completionHandler:

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

- (void)seekToTime:(CMTime)time toleranceBefore:(CMTime)toleranceBefore toleranceAfter:(CMTime)toleranceAfter completionHandler:(void (^)(BOOL finished))completionHandler
Parameters
time

The time to which you would like to move the playback cursor.

toleranceBefore

The tolerance allowed before time.

toleranceAfter

The tolerance allowed after time.

completionHandler

The block to invoke when the seek operation has either been completed or been interrupted.

The block takes one argument:

finished

Indicated whether the seek operation completed.

Discussion

Use this method to seek to a specified time for the current player item and to be notified when the seek operation is complete.

The time seeked to will be within the range [time-beforeTolerance, time+afterTolerance], and may differ from the specified time for efficiency. If you pass kCMTimeZero for both toleranceBefore and toleranceAfter (to request sample accurate seeking), you may incur additional decoding delay.

Invoking this method with toleranceBefore set to kCMTimePositiveInfinity and toleranceAfter set to kCMTimePositiveInfinity is the same as invoking seekToTime:.

The completion handler for any prior seek request that is still in process will be invoked immediately with the finished parameter set to NO. If the new request completes without being interrupted by another seek request or by any other operation the specified completion handler will be invoked with the finished parameter set to YES.

Availability
  • Available in iOS 5.0 and later.
Declared In
AVPlayer.h

setMediaSelectionCriteria:forMediaCharacteristic:

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

- (void)setMediaSelectionCriteria:(AVPlayerMediaSelectionCriteria *)criteria forMediaCharacteristic:(NSString *)mediaCharacteristic
Parameters
criteria

An instance of AVPlayerMediaSelectionCriteria that specifies the selection criteria.

mediaCharacteristic

The media characteristic for which the selection criteria are to be applied. Supported values include AVMediaCharacteristicAudible, AVMediaCharacteristicLegible, and AVMediaCharacteristicVisual.

Discussion

Criteria will be applied to an AVPlayerItem instance when:

  • It is made ready to play.

  • Specific media selections are made by the AVPlayerItem instance using the method selectMediaOption:inMediaSelectionGroup: in a different group. The automatic choice in one group may be influenced by a specific selection in another group.

  • Underlying system preferences change, e.g. system language, accessibility captions.

Specific selections made by the AVPlayerItem instance using the method selectMediaOption:inMediaSelectionGroup: method within any group will override automatic selection in that group until the player item receives a selectMediaOptionAutomaticallyInMediaSelectionGroup: message.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVPlayer.h

setRate:time:atHostTime:

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

- (void)setRate:(float)rate time:(CMTime)itemTime atHostTime:(CMTime)hostClockTime
Parameters
rate

The playback rate for the item.

itemTime

The precise time at which to match playback of the item. To use the current item’s current time, specify kCMTimeInvalid.

hostClockTime

The host time at which to synchronize playback. If you specify kCMTimeInvalid, the rate and time are set together without any external synchronization.

Discussion

This method adjusts the current item’s timebase so that the time in itemTime is in sync with the time in hostClockTime. Thus, if hostClockTime specifies a time in the past, the item’s timebase is adjusted to make it appear as if the item has been running at the specified rate since itemTime. And if hostClockTime specifies a time in the future, playback is adjusted backward (if possible) so that the value in itemTime occurs at the precise moment the host’s clock reaches the value in hostClockTime. If there is no content to play before the time specified by itemTime, playback holds until the two times come into sync.

This method does not ensure that media data is loaded before the timebase starts moving. However, if you specify a host time in the near future, that would give you some time to load the media data and prepare for playback.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVPlayer.h

Constants

AVPlayerStatus

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

enum {
   AVPlayerStatusUnknown,
   AVPlayerStatusReadyToPlay,
   AVPlayerStatusFailed
};
typedef NSInteger AVPlayerStatus;
Constants
AVPlayerStatusUnknown

Indicates that the status of the player is not yet known because it has not tried to load new media resources for playback.

Available in iOS 4.0 and later.

Declared in AVPlayer.h.

AVPlayerStatusReadyToPlay

Indicates that the player is ready to play AVPlayerItem instances.

Available in iOS 4.0 and later.

Declared in AVPlayer.h.

AVPlayerStatusFailed

Indicates that the player can no longer play AVPlayerItem instances because of an error.

The error is described by the value of the player’s error property.

Available in iOS 4.0 and later.

Declared in AVPlayer.h.

AVPlayerActionAtItemEnd

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

enum
{
   AVPlayerActionAtItemEndAdvance  = 0,
   AVPlayerActionAtItemEndPause    = 1,
   AVPlayerActionAtItemEndNone     = 2,
};
typedef NSInteger AVPlayerActionAtItemEnd;
Constants
AVPlayerActionAtItemEndAdvance

Indicates that the player should advance to the next item, if there is one.

Available in iOS 4.1 and later.

Declared in AVPlayer.h.

AVPlayerActionAtItemEndPause

Indicates that the player should pause playing.

Available in iOS 4.0 and later.

Declared in AVPlayer.h.

AVPlayerActionAtItemEndNone

Indicates that the player should do nothing.

Available in iOS 4.0 and later.

Declared in AVPlayer.h.