Detect pause/resume in ExoPlayer

左心房为你撑大大i 提交于 2019-12-03 22:32:59

You need to check playWhenReady with a Player.EventListener. The Playback states of ExoPlayer are independent from the player being paused or not:

player.addListener(new Player.DefaultEventListener() {
  @Override
  public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
    if (playWhenReady && playbackState == Player.STATE_READY) {
      // media actually playing
    } else if (playWhenReady) {
      // might be idle (plays after prepare()), 
      // buffering (plays when data available) 
      // or ended (plays when seek away from end)
    } else {
      // player paused in any state
    }
  }
});

To play/pause the player ExoPlayer provides

player.setPlayWhenReady(boolean)

The sequence of playback states with ExoPlayer with a media file which never stalls to rebuffer is once in each of the four states and does not express play/paused:

Player.STATE_IDLE;
Player.STATE_BUFFERING;
Player.STATE_READY;
Player.STATE_ENDED;

Each time the player needs to buffer it goes:

Player.STATE_READY;
Player.STATE_BUFFERING;
Player.STATE_READY;

Setting playWhenReady does not affect the state.

All together your media is actually playing when

playWhenReady && playbackState == Player.STATE_READY

It plays when ready. :)

Photon

You can use this function:

public boolean isPlaying() {
    return exoPlayer.getPlaybackState() == Player.STATE_READY && exoPlayer.getPlayWhenReady();
}

You can use exoplayer.getPlayWhenReady() to check whether the player is currently in a pause state or playing state.

I had the same requirement to detect the click event of exoplayer play/pause button. Above answers were mainly talking about the state not about the button click event.

This is what I did to detect the Play/Pause button click, works perfect.

Step 1: Create custom control dispatcher class and override the method dispatchSetPlayWhenReady

class PlayerControlDispatcher : DefaultControlDispatcher() {
    override fun dispatchSetPlayWhenReady(player: Player?, playWhenReady: Boolean): Boolean {
        if(playWhenReady) {
           // Play button clicked
        } else {
          // Paused button clicked
        }
        return super.dispatchSetPlayWhenReady(player, playWhenReady)
    }
}

Step 2: Set the custom control dispatcher class PlayerControlDispatcher into the the player view.

playerView.setControlDispatcher(PlayerControlDispatcher())

Where playerView is an instance of com.google.android.exoplayer2.ui.PlayerView which we declare in our layout file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!