Listening to Player Events
Attach Listeners
The application can listen to events such as changes in player state, buffering state, seek state and playback errors by registering a listener/delegate.
// self must conform to `PlayerDelegate` protocol
player.delegate = self;
Attach Multiple Listeners
The application can attach multiple listeners to the player and receive callbacks. The following code snippet demonstrates the same.
// delegateObject must conform to `PlayerDelegate` protocol
player.addDelegate(delegateObject);
The added delegate object could be removed as follows
// remove the added delegate
player.removeDelegate(delegateObject);
Observe Player state changes
Changes in player state can be received by implementing the following in a registered listener/delegate:
func playerStateDidChange(state: PlayerState) {
}
Leveraging swift language the player also provides observable properties. The playbackState, isSeeking and isBuffering properties could be observed for state changes.
// Observing on player playbackState property
player.playbackState.add(self) { (oldValue, newValue) in
// handle state change
}
// Remove observers on player close or player instance released
player.playbackState.remove(self)
The player can be in one of the following playback states:
PlaybackState.IDLE
: This is 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 etc.,) 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 in the process of 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
}
}
It is suggested to add and remove time observers accordingly while pausing, seeking and stopping to avoid unneccessary updates.
Handle Player Errors
Playback failures can be observed by implementing the following in a registered listener/delegate.
func playerDidFail(with error: FLError) {
}
Refer to Error Codes page for the full list of possible error codes.