如何在exoplayer中监控播放位置

How to monitor playback position in exoplayer

我正在努力寻找一种方法来创建一个线程来监视 Exoplayer 应用程序中的 playbackPosition。

在下面的代码中,我需要的一个简单任务是通过覆盖 onIsPlayingChanged 函数,每 1000 毫秒记录一次位置参数。但是我知道这只会发生一次,但是如果应用程序状态发生变化,为了使这种情况持续发生,我想我应该创建一个线程。请让我知道我怎样才能做到这一点。 如您所见,注释代码是我尝试过的代码,但肯定不对。

private class PlaybackStateListener implements Player.EventListener{

    @Override
    public void onIsPlayingChanged(boolean isPlaying) {
     //TODO: Add handler to poll the playback position continuously.
      /* if(isPlaying){
        HandlerCompat.
                postDelayed(new Runnable() {
                  @Override
                  public void run() {
                    long positionParam = playbackPosition;
                  }
                });
        }*/

      if (isPlaying) {
        Log.d(TAG, "Playing position is " + playbackPosition);
      } else {
        // Not playing because playback is paused, ended, suppressed, or the player
        // is buffering, stopped or failed. Check player.getPlaybackState,
        // player.getPlayWhenReady, player.getPlaybackError and
        // player.getPlaybackSuppressionReason for details.
      }
    }

以下代码可用于使用处理程序 postDelayed 方法解决此类问题。

final Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//My code
}
handler.postDelayed(new Runnable() {
@Override
    public void run() {
    playbackPosition = player.getCurrentPosition();
    send(playbackPosition);   //Function to update position
    handler.postDelayed(this, 1000); //1000ms frequency of updates.
    }
}, 1000);
}

Kotlin 协程方式

private fun pollCurrentDuration() = flow {
        while (player.currentPosition + DURATION_OFFSET <= player.duration) {
            emit(player.currentPosition + DURATION_OFFSET)
            delay(DEFAULT_DELAY_MS)
        }
    }.conflate()