Как показать субтитры VTT в ExoPlayer2?

#android #kotlin #exoplayer2.x #subtitle

#Android #kotlin #exoplayer2.x #субтитры

Вопрос:

Как я могу установить и показывать субтитры с URL с помощью ExoPlayer2 в Android? В настоящее время я пишу на Kotlin, я использую следующий код для настройки ExoPlayer с субтитрами:

 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()
 

И следующий код для их отображения в ExoPlayer SubtitleView:

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

Я не получаю никаких исключений, он просто ничего не показывает idk…
На самом деле ничего не работает… Действительно нужна помощь, заранее спасибо!

Комментарии:

1. привет, вы нашли решение с использованием mediaItems?

Ответ №1:

Вот код, который я использовал (я получил их из Интернета, где-то я забыл)

 // 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)
 

Комментарии:

1. Неразрешенная ссылка: createTextSampleFormat