DEV Community

Yogesh Choudhary Paliyal
Yogesh Choudhary Paliyal

Posted on • Originally published at yogeshpaliyal.com on

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'

Enter fullscreen mode Exit fullscreen mode

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"/>

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Initialize ExoPlayer object

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

set mediaItem to player

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

Enter fullscreen mode Exit fullscreen mode

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()
}

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)