Skip to main content

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;

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.

Player State Machine

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

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) {

}
note

Refer to Error Codes page for the full list of possible error codes.