[SOLVED] Exoplayer 2, How to detect subtitles change?


This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under
CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

Issue

I am developing video player on Android with ExoPlayer 2. I am looking for the way to detect subtitles change in SubtitleView(upper part of screen) to auto-scroll subtitles in TextView(lower part of screen). It looks there is no listener to do so. I tried several listener in SubtitleView but no works.
Do you have any ideas?

Here is the library of SubtitleView.

https://google.github.io/ExoPlayer/doc/reference/com/google/android/exoplayer2/ui/SubtitleView.html

This is the video player I’m developing.

https://github.com/yuseisako/TangoPlayer

This is video player I am developing

Solution

I figured this out by following simple code.

https://github.com/yuseisako/TangoPlayer/blob/master/app/src/main/java/me/yusei/tangoplayer/VideoPlayerActivity.java#L527

scrollSubtitleRunnable = new Runnable() {

    List<Caption> subtitles = new ArrayList<>(timedTextObject.captions.values());

    @Override
    public void run() {
        if(mMediaPlayer != null && mMediaPlayer.isPlaying()){
            float currentPos = mMediaPlayer.getTime();
            int index = 0;

            for (Caption caption : subtitles) {
                if (currentPos >= caption.start.mseconds - subtitleDelay
                        && currentPos <= caption.end.mseconds - subtitleDelay) {
                    listView.setItemChecked(index,true);
                    int height = listView.getHeight();
                    listView.setSelectionFromTop(index, height/2);
                    setSubtitleTextView(caption);
                    break;
                } else {
                    setSubtitleTextView(null);
                    if(currentPos < caption.end.mseconds - subtitleDelay){
                        break;
                    }
                }
                index++;
            }
        }

        scrollSubtitleHandler.postDelayed(this, 300);
    }
};
scrollSubtitleHandler.post(scrollSubtitleRunnable);

Answered By – Yusei

people found this article helpful. What about you?