Buffering the player when needed - devrath/MediaAlchemySuite GitHub Wiki

About

  • Now when the Player is buffering the medai. We should display the loader show user can see the media loading
  • We can achieve witht the help of player listener.

Code

  • Define a player listener class and pass the controller and update the player states and observe the state in view model and update the UI.
class PlayerStateListener(
    private val controller: MediaController,
    private val onPlayerStateChanged: (PlayerState) -> Unit
): Player.Listener {

    override fun onPlaybackStateChanged(playbackState: Int) {
        when (playbackState) {
            Player.STATE_BUFFERING -> onPlayerStateChanged(PlayerState.PlayerBuffering)
            Player.STATE_READY -> onPlayerStateChanged(PlayerState.PlayerReady)
            Player.STATE_ENDED -> onPlayerStateChanged(PlayerState.PlayerEnded)
        }
    }

    override fun onIsPlayingChanged(isPlaying: Boolean) {
        Log.d(APP_TAG, "isPlaying: $isPlaying")
        val suppressionReason = controller.playbackSuppressionReason
        val error = controller.playerError

        when {
            error != null -> {
                Log.e(APP_TAG, "Player error occurred: ${error.message}")
                onPlayerStateChanged(PlayerState.PlayerError(error))
            }

            suppressionReason != Player.PLAYBACK_SUPPRESSION_REASON_NONE -> {
                Log.w(APP_TAG, "Playback suppressed. Reason: $suppressionReason")
                onPlayerStateChanged(PlayerState.PlayerSuppressed(suppressionReason))
            }

            !controller.playWhenReady -> {
                Log.d(APP_TAG, "Player is paused or waiting.")
                onPlayerStateChanged(PlayerState.PlayerPaused)
            }

            isPlaying -> {
                Log.d(APP_TAG, "Playback is active.")
                onPlayerStateChanged(PlayerState.PlayerPlaying)
            }
        }
    }

    override fun onPlayerError(error: PlaybackException) {
        when (val cause = error.cause) {
            is HttpDataSource.HttpDataSourceException -> {
                when (cause) {
                    is HttpDataSource.InvalidResponseCodeException -> {
                        Log.e(APP_TAG, "HTTP error code: ${cause.responseCode}")
                    }
                    else -> Log.e(APP_TAG, "HTTP error: ${cause.message}")
                }
            }
            else -> Log.e(APP_TAG, "Playback error: ${error.message}")
        }
        onPlayerStateChanged(PlayerState.PlayerError(error))
    }

    override fun onEvents(player: Player, events: Player.Events) {
        if (events.contains(Player.EVENT_PLAYBACK_STATE_CHANGED)) {
            Log.e(APP_TAG, "OnEvents: EVENT_PLAYBACK_STATE_CHANGED")
        }
    }
}