Listening to Player Events
Attach listeners
You can listen to events such as changes in player state, buffering state, seek state, and playback errors by registering a listener or delegate.
// self must conform to `PlayerDelegate` protocol
player.delegate = self;
Attach multiple listeners
You can attach multiple listeners to the player to receive callbacks. The following code snippet demonstrates this:
// delegateObject must conform to `PlayerDelegate` protocol
player.addDelegate(delegateObject);
You can remove the added delegate object as follows:
// remove the added delegate
player.removeDelegate(delegateObject);
Observe player state changes
Receive changes in player state by implementing the following method in a registered listener or delegate:
func playerStateDidChange(state: PlayerState) {
}
The player also provides observable properties. You can observe the
playbackState, isSeeking, and isBuffering properties for state changes.
// Observe player playbackState property
player.playbackState.add(self) { (oldValue, newValue) in
// Handle state change
}
// Remove observers when you close the player or release the player instance
player.playbackState.remove(self)
The player can be in one of the following playback states:
PlaybackState.IDLE: The initial state. Indicates that the player has no media to play and doesn't hold any resources.PlaybackState.LOADING: Indicates that the player is loading the initial media chunks (manifest, initialization chunks, and so on) required to play the media source.PlaybackState.LOADED: Indicates that the player has loaded all the resources needed to start playback rendering.PlaybackState.STARTED: Indicates that the player has started rendering playback.PlaybackState.PAUSED: Indicates that the player has paused rendering playback.PlaybackState.STOPPING: Indicates that the player is stopping playback rendering.
Observing the Playback Time
Observe the playback time for an asset in order to update the player’s state.
var timeObserverToken: Any?
func addPeriodicTimeObserver() {
// Notify every half second
let timeScale = CMTimeScale(NSEC_PER_SEC)
let time = CMTime(seconds: 0.5,
preferredTimescale: timeScale)
timeObserverToken = player?.addPeriodicTimeObserver(
forInterval: time,
queue: .main) {
[weak self] time in
guard let self = self else { return }
// Update your custom player UI
}
}
func removePeriodicTimeObserver() {
if let timeObserverToken = timeObserverToken,
let player = player {
player.removeTimeObserver(timeObserverToken)
self.timeObserverToken = nil
}
}
Note: Add and remove time observers when pausing, seeking, and stopping to avoid unnecessary updates.
Handle player errors
Observe playback failures by implementing the following method in a registered listener or delegate:
func playerDidFail(with error: FLError) {
}
Note: For a full list of possible error codes, see Error codes.