Search code examples
androidandroid-viewpagerexoplayerexoplayer2.xfragmentstatepageradapter

Exoplayer - How to play only the current screen visible in FragmentStatePagerAdapter?


I am using FragmentStatePagerAdapter with Exoplayer. My main goal is to load the next page, however don't play the video in that page. Right now in my VideoFragment for the viewpager, I am playing the video inside onCreateView

player = new SimpleExoPlayer.Builder(mContext).build();
player.setPlayWhenReady(true);
player.setRepeatMode(Player.REPEAT_MODE_ONE);
playerView.setPlayer(player);

addListenerToPlayer();

DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(mContext,
           Util.getUserAgent(mContext, "yourApplicationName"));
Uri uri = Uri.parse(mUrl);

MediaSource videoSource = new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
player.prepare(videoSource);

How do I setup my exoplayer and adapter so that it only plays the current screen?


Solution

  • Replace player.setPlayWhenReady(true); with player.setPlayWhenReady(false); in your initial configuration as this instructs the player instance to play the media as soon as it's ready to be played.

    According to the docs on Player.STATE_READY:

    The player is able to immediately play from its current position. The player will be playing if getPlayWhenReady() is true, and paused otherwise.

    Moreover, you should setup either PageChangeListener or PageChangeCallback (depending on which version of ViewPager you're using) to monitor which page in the ViewPager is currently selected and which are not. For the selected page, you can set its corresponding exoplayer instance to play the video with player.setPlayWhenReady(true). It is also a good idea to pause the player in each of your fragment's onPause(...) lifecycle method.