3

How can I set and show subtitles from url with ExoPlayer2 in Android? Currently, I write in Kotlin, I'm using following code for setting up ExoPlayer with subtitles:

exoPlayer = SimpleExoPlayer.Builder(this).build()
    val subtitle = MediaItem.Subtitle(Uri.parse(SUBTITLES_URL), MimeTypes.TEXT_VTT, "en")
    val subtitles = arrayListOf(subtitle)
    val mediaItem = MediaItem.Builder()
        .setUri(movieSrc)
        .setSubtitles(subtitles)
        .build()
    exoPlayer.setMediaItem(mediaItem)
    exoPlayer.addListener(this)
    exoPlayer.prepare()

And following code to display them in ExoPlayer SubtitleView:

exoPlayer.addTextOutput {
        binding.exoSubtitles.onCues(it)
    }

I don't get any exception, it just does not show anything idk... Nothing really works... Really need some help, Thank You in Advance!

Zoe
  • 27,060
  • 21
  • 118
  • 148
grgg7
  • 91
  • 2
  • 10

1 Answers1

4

Here is the code I used (I got these from the Internet somewhere I forgot)

// create the simple cache
val leastRecentlyUsedCacheEvictor = LeastRecentlyUsedCacheEvictor(MAX_CACHE_SIZE)
val databaseProvider: DatabaseProvider = ExoDatabaseProvider(this)
val simpleCache = SimpleCache(cacheDir, leastRecentlyUsedCacheEvictor, databaseProvider)


// create http datasource
val defaultBandwidthMeter = DefaultBandwidthMeter.Builder(context).build()
val dataSourceFactory: DataSource.Factory = DefaultDataSourceFactory(
            context,
            DefaultHttpDataSourceFactory(
                System.getProperty("http.agent"),
                defaultBandwidthMeter
            )
        )

// create the player
val simplePlayer = ExoPlayerFactory.newSimpleInstance(context)
        simplePlayer.addListener(playerCallback)
        cacheDataSourceFactory = CacheDataSourceFactory(
            simpleCache,
            DefaultHttpDataSourceFactory(
                Util.getUserAgent(
                    context,
                    "exo"
                )
            )
        )

// create subtitle text format
val textFormat = Format.createTextSampleFormat(
                    null,
                    MimeTypes.TEXT_VTT,
                    C.SELECTION_FLAG_DEFAULT,
                    null
                )
// create the subtitle source
val subtitleSource = SingleSampleMediaSource.Factory(dataSourceFactory)
  .createMediaSource(Uri.parse(it), textFormat, C.TIME_UNSET)
                
// create the media source based from video/audio url
val mediaSource = ProgressiveMediaSource.Factory(cacheDataSourceFactory).createMediaSource(uri) 

// merge subtitle source and media source   
val mediaSourceWithsubtitle = MergingMediaSource(mediaSource, subtitleSource)

// setup the player
simplePlayer.prepare(mediaSourceWithsubtitle, true, true)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Putra
  • 126
  • 2
  • 11