iOS Developer Library — Prerelease

Developer

AV Foundation Framework Reference AVPlayer Class Reference

Options
Deployment Target:

On This Page
Language:

AVPlayer

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.

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

    Declaration

    Swift

    init(URL URL: NSURL)

    Objective-C

    - (instancetype _Nonnull)initWithURL:(NSURL * _Nonnull)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.

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

    Declaration

    Objective-C

    + (instancetype _Nonnull)playerWithURL:(NSURL * _Nonnull)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.

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

    Declaration

    Swift

    init(playerItem item: AVPlayerItem)

    Objective-C

    - (instancetype _Nonnull)initWithPlayerItem:(AVPlayerItem * _Nonnull)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.

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

    Declaration

    Objective-C

    + (instancetype _Nonnull)playerWithPlayerItem:(AVPlayerItem * _Nonnull)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.

  • Begins playback of the current item.

    Declaration

    Swift

    func play()

    Objective-C

    - (void)play

    Discussion

    This is the same as setting rate to 1.0.

    Availability

    Available in iOS 4.0 and later.

    See Also

    rate

  • Pauses playback.

    Declaration

    Swift

    func pause()

    Objective-C

    - (void)pause

    Discussion

    This is the same as setting rate to 0.0.

    Availability

    Available in iOS 4.0 and later.

    See Also

    rate

  • rate rate Property

    The current rate of playback.

    Declaration

    Swift

    var rate: Float

    Objective-C

    @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 YEStrue for the AVPlayerItem properties canPlaySlowForward or canPlayFastForward. Negative rate value ranges are supported if the player item returns YEStrue for the canPlayReverse, canPlaySlowReverse, and canPlayFastReverse properties.

    Availability

    Available in iOS 4.0 and later.

    See Also

    – play
    – pause
    canPlayFastForward (AVPlayerItem Class)
    canPlaySlowForward (AVPlayerItem Class)
    canPlayReverse (AVPlayerItem Class)
    canPlaySlowReverse (AVPlayerItem Class)
    canPlayFastReverse (AVPlayerItem Class)

  • The action to perform when an item has finished playing.

    Declaration

    Swift

    var actionAtItemEnd: AVPlayerActionAtItemEnd

    Objective-C

    @property(nonatomic) AVPlayerActionAtItemEnd actionAtItemEnd

    Discussion

    For possible values, see AVPlayerActionAtItemEnd.

    Availability

    Available in iOS 4.0 and later.

  • Replaces the player item with a new player item.

    Declaration

    Swift

    func replaceCurrentItemWithPlayerItem(_ item: AVPlayerItem?)

    Objective-C

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

    Parameters

    item

    A player item.

    Discussion

    This method must only be invoked on player instances created without queues. If the player is initialized with multiple items the method throws an exception.

    The item replacement occurs immediately, the item becomes the player’s currentItem.

    Using the replaceCurrentItemWithPlayerItem: method to replace the player's currentItem with itself does nothing. In iOS 4.0 and earlier, attempting this raised an exception.

    Use key-value observing to observe the currentItem property for changes.

    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.

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

    Declaration

    Swift

    func prerollAtRate(_ rate: Float, completionHandler completionHandler: ((Bool) -> Void)?)

    Objective-C

    - (void)prerollAtRate:(float)rate completionHandler:(void (^ _Nullable)(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 YEStrue if the data was loaded or NOfalse if there was a problem. For example, the value might be NOfalse 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.

  • Cancels the preloading of media data.

    Declaration

    Swift

    func cancelPendingPrerolls()

    Objective-C

    - (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.

  • Returns the current time of the current item.

    Declaration

    Swift

    func currentTime() -> CMTime

    Objective-C

    - (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.

  • Moves the playback cursor to a given time.

    Declaration

    Swift

    func seekToTime(_ time: CMTime)

    Objective-C

    - (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.

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

    Declaration

    Swift

    func seekToDate(_ date: NSDate)

    Objective-C

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

    Parameters

    date

    The time at which to move the playback cursor.

    Availability

    Available in iOS 6.0 and later.

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

    Declaration

    Swift

    func seekToTime(_ time: CMTime, completionHandler completionHandler: (Bool) -> Void)

    Objective-C

    - (void)seekToTime:(CMTime)time completionHandler:(void (^ _Nonnull)(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 YEStrue.

    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 NOfalse.

    Availability

    Available in iOS 5.0 and later.

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

    Declaration

    Swift

    func seekToDate(_ date: NSDate, completionHandler completionHandler: (Bool) -> Void)

    Objective-C

    - (void)seekToDate:(NSDate * _Nonnull)date completionHandler:(void (^ _Nonnull)(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 YEStrue.

    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 NOfalse.

    Availability

    Available in iOS 5.0 and later.

  • Moves the playback cursor within a specified time bound.

    Declaration

    Swift

    func seekToTime(_ time: CMTime, toleranceBefore toleranceBefore: CMTime, toleranceAfter toleranceAfter: CMTime)

    Objective-C

    - (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.

  • 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.

    Declaration

    Swift

    func seekToTime(_ time: CMTime, toleranceBefore toleranceBefore: CMTime, toleranceAfter toleranceAfter: CMTime, completionHandler completionHandler: (Bool) -> Void)

    Objective-C

    - (void)seekToTime:(CMTime)time toleranceBefore:(CMTime)toleranceBefore toleranceAfter:(CMTime)toleranceAfter completionHandler:(void (^ _Nonnull)(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 NOfalse. 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 YEStrue.

    Availability

    Available in iOS 5.0 and later.

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

    Declaration

    Swift

    var allowsExternalPlayback: Bool

    Objective-C

    @property(nonatomic) BOOL allowsExternalPlayback

    Discussion

    The default value of this property is YEStrue.

    Availability

    Available in iOS 6.0 and later.

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

    Declaration

    Swift

    var externalPlaybackActive: Bool { get }

    Objective-C

    @property(nonatomic, readonly, getter=isExternalPlaybackActive) BOOL externalPlaybackActive

    Availability

    Available in iOS 6.0 and later.

  • 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.

    Declaration

    Swift

    var usesExternalPlaybackWhileExternalScreenIsActive: Bool

    Objective-C

    @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 NOfalse. The value of this property has no effect if allowsExternalPlayback is NOfalse.

    Availability

    Available in iOS 6.0 and later.

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

    Declaration

    Swift

    var externalPlaybackVideoGravity: String

    Objective-C

    @property(nonatomic, copy) NSString * _Nonnull externalPlaybackVideoGravity

    Availability

    Available in iOS 6.0 and later.

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

    Declaration

    Swift

    func setRate(_ rate: Float, time itemTime: CMTime, atHostTime hostClockTime: CMTime)

    Objective-C

    - (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.

  • The master clock used for item timebases.

    Declaration

    Swift

    var masterClock: CMClock?

    Objective-C

    @property(nonatomic, retain) CMClockRef _Nullable 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.

  • Indicates whether the player uses closed captioning.

    Declaration

    Swift

    var closedCaptionDisplayEnabled: Bool

    Objective-C

    @property(nonatomic, getter=isClosedCaptionDisplayEnabled) BOOL closedCaptionDisplayEnabled

    Availability

    Available in iOS 4.0 and later.

  • Indicates whether the audio output of the player is muted.

    Declaration

    Swift

    var muted: Bool

    Objective-C

    @property(nonatomic, getter=isMuted) BOOL muted

    Availability

    Available in iOS 7.0 and later.

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

    Declaration

    Swift

    var volume: Float

    Objective-C

    @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.

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

    Declaration

    Swift

    var status: AVPlayerStatus { get }

    Objective-C

    @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

    error

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

    Declaration

    Swift

    var error: NSError? { get }

    Objective-C

    @property(nonatomic, readonly) NSError * _Nullable 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

    status

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

    Declaration

    Swift

    var currentItem: AVPlayerItem? { get }

    Objective-C

    @property(nonatomic, readonly) AVPlayerItem * _Nullable currentItem

    Availability

    Available in iOS 4.0 and later.

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

    Declaration

    Swift

    var outputObscuredDueToInsufficientExternalProtection: Bool { get }

    Objective-C

    @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 NOfalse.

    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.

  • airPlayVideoActive (iOS 6.0) Property

    Indicates whether the player is currently playing video through AirPlay. (read-only)

    Declaration

    Objective-C

    @property(nonatomic, readonly, getter=isAirPlayVideoActive) BOOL airPlayVideoActive

    Availability

    Available in iOS 5.0 and later.

    Deprecated in iOS 6.0.

  • allowsAirPlayVideo (iOS 6.0) Property

    Indicates whether the player allows AirPlay video playback.

    Declaration

    Objective-C

    @property(nonatomic) BOOL allowsAirPlayVideo

    Discussion

    The default value is YEStrue.

    Availability

    Available in iOS 5.0 and later.

    Deprecated in iOS 6.0.

  • Indicates whether the player should automatically switch to AirPlay Video while AirPlay Screen is active in order to play video content, switching back to AirPlay Screen as soon as playback is done.

    Declaration

    Objective-C

    @property(nonatomic) BOOL usesAirPlayVideoWhileAirPlayScreenIsActive

    Discussion

    The default value is NOfalse.

    This property has no effect if allowsAirPlayVideo is NOfalse.

    Availability

    Available in iOS 5.0 and later.

    Deprecated in iOS 6.0.

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

    Declaration

    Swift

    enum AVPlayerStatus : Int { case Unknown case ReadyToPlay case Failed }

    Objective-C

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

    Constants

    • Unknown

      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.

    • ReadyToPlay

      AVPlayerStatusReadyToPlay

      Indicates that the player is ready to play AVPlayerItem instances.

      Available in iOS 4.0 and later.

    • Failed

      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.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 4.0 and later.

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

    Declaration

    Swift

    enum AVPlayerActionAtItemEnd : Int { case Advance case Pause case None }

    Objective-C

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

    Constants

    • Advance

      AVPlayerActionAtItemEndAdvance

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

      Available in iOS 4.1 and later.

    • Pause

      AVPlayerActionAtItemEndPause

      Indicates that the player should pause playing.

      Available in iOS 4.0 and later.

    • None

      AVPlayerActionAtItemEndNone

      Indicates that the player should do nothing.

      Available in iOS 4.0 and later.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 4.0 and later.