Exoplayer in Android
Exoplayer in Android
14 April 2021
Introduction
Exoplayer is a media player for playing audio and video both locally and over the internet in Android. This exoplayer is far more better than Android’s Media Player, it is highly customizable and extensible. Exoplayer is an open source project used in YouTube as well.
Getting Started
Adding Exoplayer Dependency:
Make sure you have Google and Jcenter repositories in your project level build.gradle file.
repositories { google() jcenter() }
Add dependency of exoplayer in app module build.gradle file.
implementation ‘com.google.android.exoplayer:exoplayer:X.X.X’
Add View for Player and Creating Player:
Create activity for the player and its respective layout resource file.
XML file should be as below:
<com.google.android.exoplayer2.ui.PlayerView android:id="@+id/custom_id" android:layout_width="match_parent" android:layout_height="match_parent"/>
Create a new view variable for player view and set the player view to the assigned variable in onCreate() method.
playerView = findViewById(R.id.custom_id);
For creating the player we need an exoplayer object and we get it from SimpleExoPlayer.Builder.
SimpleExoPlayer player = new SimpleExoPlayer.Builder(context).build(); playerView.setPlayer(player); //Attaching player to its view
Preparing Player:
Now we need the content to stream and we have a Media Item for that.
MediaItem mediaItem = MediaItem.fromUri(url_string); player.setMediaItem(mediaItem); player.prepare(); player.play();
Using the above code you simply play the video content. For advancement we have player controllers, player events using which we can customize the player and extent to more advancement.
Player Events Listener
At a certain level we need the information of what the exoplayer is doing, we need an exoplayer facing some issue while streaming the content. That information we will get through the event listeners.
There are following 4 states of exoplayer, exoplayer will be found in any one of the following states.
- Player.STATE_IDLE
- Player.STATE_BUFFERING
- Player.STATE_READY
- Player.STATE_ENDED
We receive player state by implementing Player.EventListener interface and overriding onPlaybackStateChanged() method, shown as follows.
private class PlyrStateListenerClass implements Player.EventListener { @Override public void onPlaybackStateChanged(int playbackState) { //player state } }
Custom User Interface
Controllers:
You can hide/show controls on the player screen. You only have to update the flag on the resource file.
app:use_controller=”false”
You also can set the forward and rewind time as follows:
app:fastforward_increment="time_in_millis" app:rewind_increment="time_in_millis"
You can add the views for different buttons on the video player by updating the resource file of the player. Different buttons like CC button, next/previous program buttons, etc.