ExoPlayer : Getting Started

ExoPlayer : Getting Started

Exoplayer is a Powerfull MediaPlayer Library that is developed by Google and better than the MediaPlayer API.

It has many advantages over MediaPlayer API.

It is used by many video platform applications like Youtube, Netflix, etc.

First thing first: Add Dependency

implementation 'com.google.android.exoplayer:exoplayer:2.13.3'

Add Player to UI

<com.google.android.exoplayer2.ui.PlayerView
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    android:id="@+id/videoPlayer"/>

for now we are using default controller and player, we can customize as per requirement, we will create our custom controller in future posts.

Initialize Player

Declare a video player global variable

private var mPlayer: SimpleExoPlayer? = null

Initialize ExoPlayer object

mPlayer = SimpleExoPlayer.Builder(this).build()

Create A MediaItem : mediaItem is used to give source of video to play, here videoUrl is the Uri of the video.

val mediaItem = MediaItem.Builder()
    .setUri(videoUrl)
    .build()

set mediaItem to player

mPlayer?.setMediaItem(mediaItem)
mPlayer?.playWhenReady = true
binding.videoPlayer.player = mPlayer
mPlayer?.prepare()

playWhenReady : It starts video playback when video is ready to play

binding.videoPlayer.player \= mPlayer : Attack player to UI

mPlayer?.prepare() : It will start preparing player to stating playing the video

Free up resources

override fun onDestroy() {
    mPlayer?.release()
    mPlayer = null
    super.onDestroy()
}

mPlayer?.release() : This will release the memory taken by the player

Check out the source code on GitHub

Source Code

The post ExoPlayer : Getting Started appeared first on TechPaliyal.