ANDROID EXOPLAYER EXAMPLE
Android ExoPlayer Example: Implementing Media Playback with ExoPlayer
ExoPlayer is a powerful media player library for Android that provides smooth playback of audio and video files. It’s highly flexible, supports a variety of media formats, and is designed to handle features like adaptive streaming (HLS, DASH, etc.), offline playback, and content protection. ExoPlayer is used extensively in apps that require media playback capabilities, including video streaming platforms, music players, and more.
In this article, we'll walk through a basic example of how to integrate ExoPlayer into an Android app for video playback.
What is ExoPlayer?
ExoPlayer is an open-source media player for Android developed by Google. It offers a high level of performance and flexibility compared to the default Android MediaPlayer. ExoPlayer supports many features like:
- Streaming of media files in different formats (MP4, MP3, HLS, DASH, etc.)
- Advanced media controls (playback, seeking, looping, etc.)
- Offline support for downloading media content
- Wide range of customization options (such as video rendering, audio track selection, etc.)
It is ideal for scenarios where the default Android MediaPlayer doesn't meet the needs for handling adaptive streams or specific formats.
Setting up ExoPlayer in Android
To integrate ExoPlayer into your Android project, you’ll need to perform the following steps:
Step 1: Add Dependencies to build.gradle
First, you need to add the ExoPlayer dependencies to your project’s build.gradle file.
- Open your project in Android Studio.
- Navigate to the
appmodule'sbuild.gradlefile (not the top-level one). - Add the following dependencies under
dependencies:
implementation 'com.google.android.exoplayer:exoplayer:2.18.1' // Latest version
ExoPlayer has various modules that you can include based on your needs. For general use, the dependency above will be sufficient.
Step 2: Update AndroidManifest.xml
ExoPlayer doesn’t require any special permissions for media playback (apart from those needed for the media source, like internet permissions if streaming from a URL). However, you should ensure that your app has internet access if streaming online content. In that case, add the following permissions in your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 3: Initialize ExoPlayer in the Activity or Fragment
Now let’s set up a basic ExoPlayer implementation. We'll create a simple activity with a PlayerView (a built-in view that ExoPlayer provides) to display a video.
Here’s the basic setup in an activity:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- ExoPlayer PlayerView -->
<com.google.android.exoplayer2.ui.PlayerView
android:id="@+id/playerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Step 4: Create ExoPlayer Instance and Load Media
In the activity, we'll initialize the ExoPlayer instance, set up the media source (video or audio file), and attach the player to the PlayerView.
MainActivity.java:
package com.example.exoplayerexample;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector;
public class MainActivity extends AppCompatActivity {
private ExoPlayer exoPlayer;
private PlayerView playerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize ExoPlayer
playerView = findViewById(R.id.playerView);
exoPlayer = new ExoPlayer.Builder(this).build();
// Set up the media source (for example, a video file URL)
String videoUrl = "https://path-to-your-video-file.mp4"; // Replace with your URL
MediaItem mediaItem = MediaItem.fromUri(videoUrl);
// Create a media source using ProgressiveMediaSource for a video
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this, "ExoPlayerExample");
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
.createMediaSource(mediaItem);
// Set the media source and prepare the player
exoPlayer.setMediaSource(mediaSource);
exoPlayer.prepare();
// Attach the player to the PlayerView
playerView.setPlayer(exoPlayer);
// Start the playback
exoPlayer.play();
}
@Override
protected void onPause() {
super.onPause();
// Release the ExoPlayer when the activity is paused
exoPlayer.release();
}
}
Explanation:
- PlayerView: This is a UI element that ExoPlayer provides, which handles rendering of the video. It’s similar to a
VideoView, but with more features. - ExoPlayer Initialization: We initialize
ExoPlayerusingExoPlayer.Builder(). We create a player instance that can handle playback. - Media Item: We create a
MediaItemfor the video URL. This is used to specify the media file to play. - MediaSource: ExoPlayer requires a
MediaSourceto manage and provide media for playback. We use aProgressiveMediaSourcefor streaming media such as MP4 files. - DataSourceFactory: A
DefaultDataSourceFactoryis used to fetch data from a URL (in this case, the video file). - Player Setup: Once the media source is created, we set it on the ExoPlayer instance and prepare the player. We also attach the
ExoPlayerinstance to thePlayerView. - Playback: After preparation, we start the playback using
exoPlayer.play().
Step 5: Handling Player Lifecycle
It’s important to manage the player lifecycle properly to prevent memory leaks and to ensure that the player is released when the activity or fragment is paused or destroyed.
In the example above, we released the player in the onPause() method of the Activity:
@Override
protected void onPause() {
super.onPause();
exoPlayer.release(); // Release the player to avoid memory leaks
}
In a real app, you might want to handle other lifecycle methods, like onResume() or onStop(), to pause or resume playback as needed.
Step 6: Advanced Features (Optional)
ExoPlayer has many advanced features that you might want to implement depending on your needs:
- Handling Adaptive Streaming: ExoPlayer supports formats like HLS (HTTP Live Streaming) and DASH (Dynamic Adaptive Streaming over HTTP). You can use
HlsMediaSourceorDashMediaSourceto handle streaming. - Offline Playback: You can implement offline playback by downloading media and storing it locally, using the
DownloadManagerfrom ExoPlayer. - Custom Controls: You can add custom controls to the
PlayerViewor create your own player UI. - Error Handling: It’s essential to implement error handling in ExoPlayer to manage issues such as network problems or unsupported media formats.
For example, for HLS streaming, you can use:
HlsMediaSource hlsMediaSource = new HlsMediaSource.Factory(dataSourceFactory)
.createMediaSource(MediaItem.fromUri("https://path-to-your-hls-stream.m3u8"));
Conclusion
ExoPlayer is an excellent choice for developers who need to implement media playback in their Android apps. With support for a wide range of formats, adaptive streaming, and offline capabilities, ExoPlayer is highly customizable and powerful.
In this example, we’ve demonstrated how to integrate ExoPlayer into a basic Android app to play video. You can extend this setup to add more advanced features like background playback, error handling, or playback controls. By using ExoPlayer, you can create a seamless and flexible media experience for your Android app’s users.

0 Comments