Android how to add subtitles to Media Player

1.9k Views Asked by At

I know that in Android exists special class for making video\audio players - MediaPlayer.

Is there are any build-in ways to add subtitles to playing video?

I've looked through documentation, but found no methods for subtitles.

1

There are 1 best solutions below

0
On

Yes, there is the method to add subtitle in video player addTimedTextSource

  • Example
try {
    mediaPlayer.addTimedTextSource(subTitleSrc, MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
} catch (IOException e) {
    e.printStackTrace();
}


int textTrackIndex = findTrackIndexFor(
        mediaPlayer.getTrackInfo());
Log.i("Subtitle Track index : ", "After add :: " + textTrackIndex);

if (textTrackIndex >= 0) {
    mediaPlayer.selectTrack(textTrackIndex);
} else {
    Log.w("test", "Cannot find text track!");
}

mediaPlayer.setOnTimedTextListener(new MediaPlayer.OnTimedTextListener() {
    @Override
    public void onTimedText(final MediaPlayer mediaPlayer, final TimedText timedText) {
        if (timedText != null) {
            Log.d("test", "subtitle: " + timedText.getText());
            tv_subtitle.setText(timedText.getText());
        }
    }
});    

here mediaPlayer is object of android-MediaPlayer class and subTitleSrc path of subtitle file.