svarog
svarog

Reputation: 696

Google ExoPlayer guide

I am struggling to build basic app with ExoPlayer.

hello, well, i have problem with "getting started" part. don't know what need to use in order to play video or stream. how to stop,play,pause... Another problem is that I don't know what I am providing , for example, in DefaultDataSourceFactory constructor, why, what I am getting with and without some params... I am pretty confused with whole usage... please help! thanks!

Upvotes: 3

Views: 7154

Answers (2)

Halil Ozel
Halil Ozel

Reputation: 3312

The most recent usage is as follows:

Step-1: Dependency added in build.gradle:

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

Step-2: activity_main.xml file edited.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:argType="http://schemas.android.com/tools"
    android:id="@+id/flRoot"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:keepScreenOn="true">

    <com.google.android.exoplayer2.ui.StyledPlayerView
        android:id="@+id/playerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:show_subtitle_button="true"
        argType:fastforward_increment="15000"
        argType:resize_mode="fixed_width"
        argType:rewind_increment="15000"
        argType:show_buffering="when_playing"
        argType:show_fastforward_button="true"
        argType:show_next_button="false"
        argType:show_previous_button="false"
        argType:show_rewind_button="true"
        argType:show_subtitle_button="true"
        argType:use_artwork="true"
        argType:use_controller="true"
        argType:use_sensor_rotation="true">
    </com.google.android.exoplayer2.ui.StyledPlayerView>

</FrameLayout>

Step-3: ExoPlayer adjustments made in MainActivity.kt

class MainActivity : Activity() {

    private lateinit var binding: ActivityMainBinding
    private var exoPlayer: ExoPlayer? = null
    private var playbackPosition = 0L
    private var playWhenReady = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        preparePlayer()
    }

    private fun preparePlayer() {
        exoPlayer = ExoPlayer.Builder(this).build()
        exoPlayer?.playWhenReady = true
        binding.playerView.player = exoPlayer
        val defaultHttpDataSourceFactory = DefaultHttpDataSource.Factory()
        val mediaItem =
            MediaItem.fromUri(URL)
        val mediaSource =
            HlsMediaSource.Factory(defaultHttpDataSourceFactory).createMediaSource(mediaItem)
        exoPlayer?.setMediaSource(mediaSource)
        exoPlayer?.seekTo(playbackPosition)
        exoPlayer?.playWhenReady = playWhenReady
        exoPlayer?.prepare()
    }

    private fun releasePlayer() {
        exoPlayer?.let { player ->
            playbackPosition = player.currentPosition
            playWhenReady = player.playWhenReady
            player.release()
            exoPlayer = null
        }
    }

    override fun onStop() {
        super.onStop()
        releasePlayer()
    }

    override fun onPause() {
        super.onPause()
        releasePlayer()
    }

    override fun onDestroy() {
        super.onDestroy()
        releasePlayer()
    }

    companion object {
        const val URL =
            "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8"
    }
}

You can access the project on GitHub: https://github.com/halilozel1903/ExoPlayerDemo

Upvotes: 1

Mayur_Thakur
Mayur_Thakur

Reputation: 661

First you need to add this in your build.gradle
compile 'com.google.android.exoplayer:exoplayer:r2.1.1'

1. Your Layout File

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <com.google.android.exoplayer2.ui.SimpleExoPlayerView
        android:id="@+id/player_view"
        android:focusable="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

2. Your Class File

public class ExoPlayerActivity extends AppCompatActivity implements ExoPlayer.EventListener {
        SimpleExoPlayer player;
        String path;        // it can be url of video for online streaming or a url of local video

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_exoplayer);

            // set your path here
            path=<your path>;

            // 1. Create a default TrackSelector
            BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
            TrackSelection.Factory videoTrackSelectionFactory =
                    new AdaptiveVideoTrackSelection.Factory(bandwidthMeter);
            TrackSelector trackSelector =
                    new DefaultTrackSelector(videoTrackSelectionFactory);

            // 2. Create a default LoadControl
            LoadControl loadControl = new DefaultLoadControl();
            // 3. Create the player
            player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);

            SimpleExoPlayerView playerView = (SimpleExoPlayerView) findViewById(R.id.player_view);
            playerView.setPlayer(player);
            playerView.setKeepScreenOn(true);
            // Produces DataSource instances through which media data is loaded.
            DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "ExoPlayer"));

            // Produces Extractor instances for parsing the media data.
            ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();

            // This is the MediaSource representing the media to be played.
            MediaSource videoSource = new ExtractorMediaSource(Uri.parse(path),
                    dataSourceFactory, extractorsFactory, null, null);
            // Prepare the player with the source.
            player.addListener(this);
            player.prepare(videoSource);
            playerView.requestFocus();
            player.setPlayWhenReady(true);      // to play video when ready. Use false to pause a video
        }


        @Override
        protected void onPause() {
            super.onPause();
            if (player != null) {
                player.setPlayWhenReady(false); //to pause a video because now our video player is not in focus
            }
        }

        @Override
        public void onTimelineChanged(Timeline timeline, Object manifest) {

        }

        @Override
        public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {

        }

        @Override
        public void onLoadingChanged(boolean isLoading) {

        }

        @Override
        public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
            switch (playbackState) {
                case ExoPlayer.STATE_BUFFERING:
                    //You can use progress dialog to show user that video is preparing or buffering so please wait
                    break;
                case ExoPlayer.STATE_IDLE:
                    //idle state
                    break;
                case ExoPlayer.STATE_READY:
                    // dismiss your dialog here because our video is ready to play now
                    break;
                case ExoPlayer.STATE_ENDED:
                    // do your processing after ending of video
                    break;
            }
        }

        @Override
        public void onPlayerError(ExoPlaybackException error) {
            // show user that something went wrong. I am showing dialog but you can use your way
            AlertDialog.Builder adb = new AlertDialog.Builder(ExoPlayerActivity.this);
            adb.setTitle("Could not able to stream video");
            adb.setMessage("It seems that something is going wrong.\nPlease try again.");
            adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish(); // take out user from this activity. you can skip this
                }
            });
            AlertDialog ad = adb.create();
            ad.show();
        }

        @Override
        public void onPositionDiscontinuity() {
            //Video is not streaming properly
            Log.d("Mayur", "Discontinuity");
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            player.release();   //it is important to release a player
        }
    }

I think this is enough for beginner. Also keep in mind that this library's standard audio and video components rely on Android’s MediaCodec API, which was released in Android 4.1 (API level 16). So it will not work on android 4.0 and below.

Upvotes: 23

Related Questions