AVPlayer Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/AVFoundation.framework
Availability
Available in OS X v10.7 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.

Tasks

Creating a Player

Managing Playback

Managing Time

Synchronizing Playback to an External Source

Timed Observations

Managing Closed Caption Display

Managing Audio Output

Player Properties

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 OS X v10.7 and later.
Declared In
AVPlayer.h

closedCaptionDisplayEnabled

Indicates whether the player uses closed captioning.

@property(nonatomic, getter=isClosedCaptionDisplayEnabled) BOOL closedCaptionDisplayEnabled
Availability
  • Available in OS X v10.7 and later.
Declared In
AVPlayer.h

currentItem

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

@property(nonatomic, readonly) AVPlayerItem *currentItem
Availability
  • Available in OS X v10.7 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 OS X v10.7 and later.
Declared In
AVPlayer.h

masterClock

The master clock used for item timebases.

@property (nonatomic, retain) __attribute__((NSObject)) 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 OS X v10.8 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 OS X v10.7 and later.
Declared In
AVPlayer.h

rate

The current rate of playback.

@property(nonatomic) float rate
Discussion

0.0 means “stopped”, 1.0 means “play at the natural rate of the current item”.

Availability
  • Available in OS X v10.7 and later.
Related Sample Code
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 OS X v10.7 and later.
Declared In
AVPlayer.h

volume

Indicates the current audio volume of the player.

@property(nonatomic) float volume
Discussion

0.0 means “silence all audio,” 1.0 means “play at the full volume of the current item.”

Availability
  • Available in OS X v10.7 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 OS X v10.7 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 OS X v10.7 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) 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 OS X v10.7 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) 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 OS X v10.7 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 OS X v10.8 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 OS X v10.7 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 OS X v10.7 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 OS X v10.7 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 OS X v10.7 and later.
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 OS X v10.7 and later.
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 OS X v10.8 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 OS X v10.7 and later.
Related Sample Code
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 OS X v10.7 and later.
Related Sample Code
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 OS X v10.7 and later.
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 OS X v10.7 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 OS X v10.7 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 OS X v10.7 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 OS X v10.8 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 OS X v10.7 and later.

Declared in AVPlayer.h.

AVPlayerStatusReadyToPlay

Indicates that the player is ready to play AVPlayerItem instances.

Available in OS X v10.7 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 OS X v10.7 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 OS X v10.7 and later.

Declared in AVPlayer.h.

AVPlayerActionAtItemEndPause

Indicates that the player should pause playing.

Available in OS X v10.7 and later.

Declared in AVPlayer.h.

AVPlayerActionAtItemEndNone

Indicates that the player should do nothing.

Available in OS X v10.7 and later.

Declared in AVPlayer.h.


Did this document help you? Yes It's good, but... Not helpful...