State & Events
Every io.video.videokit.player.Player
implementation keeps its internal state and
offers a way to register listener objects to listen to important events.
Player state
The player state can be retrieved with player.state
and, similar to our recorder
component, matches one of the constants in the io.video.videokit.player.PlayerState
class:
State | Description | Has content | Is playing |
---|---|---|---|
PlayerState.Idle | Player has no content. | false | false |
PlayerState.Buffering | Player has content and will play it as soon as buffering is finished. | true | true |
PlayerState.Playing | Player has content and is playing it. | true | true |
PlayerState.Paused | Player has content and is ready to play it as soon as play() is called. | true | false |
PlayerState.PausedBuffering | Player has content but it is ready to play it. | true | false |
Player events
All Player
events are dispatched to a io.video.videokit.player.Player.Observer
that was
previously registered using addObserver
or similar function.
player.observeIn(lifecycle, observer) // start listening, stops automatically
player.observeIn(coroutineJob, observer) // start listening, stops automatically
player.addObserver(observer) // start listening, remember to remove later
player.removeObserver(observer) // stop listening
Observers are very important to be up-to-date about the player state, handle errors and create a responsive UI. We describe the observer interface as comments in the interface description below.
interface Player.Observer {
// Player state has changed - see constants in the State class.
fun onStateChanged(state: PlayerState) = Unit
// Playback failed due to some error.
fun onError(error: VideoKitException) = Unit
// The content duration has changed, likely because content itself
// has changed. This can be used to display a duration UI element.
fun onDurationChanged(durationMs: Long) = Unit
// The playback position has changed. This is invoked many times during
// playback to implement a smooth UI seekbar, for example.
fun onPositionChanged(positionMs: Long) = Unit
// The playback buffered position has changed. This is invoked many times
// as the video is being played and loaded, and can be shown in a UI element.
fun onBufferedPositionChanged(bufferedPositionMs: Long) = Unit
// The player.mute value has been changed.
fun onMuteChanged(mute: Boolean) = Unit
// The content is ready to be played using play().
fun onPlaybackReady() = Unit
// The playback has reached the end of the content.
fun onPlaybackFinished() = Unit
}
Coroutines
For kotlinx.coroutines
users, note that all the reactive properties that are dispatched to the observers
are also available as a Flow
and StateFlow
.
player.stateFlow
.onEach { /* state changed */ }
.launchIn(scope)
player.errorFlow
.onEach { /* something went wrong */ }
.launchIn(scope)
// And more