October 23, 2024
Chicago 12, Melborne City, USA
Android

Play ads at specific times of the video in ExoPlayer and using IMA extension


In Android (kotlin) am using ExoPlayer 2.18.1 to stream movies, and in order to add ads to these movies i used IMA extension adsLoader to load ads and play them, currently I am using only a test adTagUrl, and the ads are playing before the video starts playing (preroll).

Is there a way to play ads at specific times of the video?
for example I want to play the ad after 60 seconds of the video start

Another thing that i cant achieve is to play ads multiple times,
I have some long videos, and I want to play multiple ads on them

I have looked for ways to manually load and start ads but i could not found any.

This is my current code to stream movies and inject ads to them:

val trackSelectorParameters = DefaultTrackSelector.ParametersBuilder(this).build()
        val trackSelector = DefaultTrackSelector(this)
        trackSelector.parameters = trackSelectorParameters
        videoUrl = playerData.url
        val videoUri = Uri.parse(videoUrl)
        val adTagUri = Uri.parse(getString(R.string.ad_tag_url))

        mediaItem = MediaItem.Builder()
            .setUri(videoUri)
            .setAdsConfiguration(AdsConfiguration.Builder(adTagUri).build())
            .build()

        player = ExoPlayer.Builder(this)
            .setTrackSelector(trackSelector)
            .build()
        adsLoader!!.setPlayer(player)

        activityPlayerBinding.playerView.player = player
        player!!.trackSelectionParameters = player!!.trackSelectionParameters
            .buildUpon()
            .setMaxVideoSizeSd()
            .setPreferredAudioLanguage("hu")
            .build();
        player!!.addListener(PlayerEventListener(this))
        activityPlayerBinding.playerView.setControllerVisibilityListener {
            if(it == 0) activityPlayerBinding.playerOptions.visibility = View.VISIBLE
            else activityPlayerBinding.playerOptions.visibility = View.GONE
        }

        mediaSource = DefaultMediaSourceFactory(this)
            .setAdsLoaderProvider { adsLoader }
            .setAdViewProvider(playerView)
            .createMediaSource(mediaItem)
        player?.let {
            it.setMediaSource(mediaSource)
            it.seekTo(TimeUnit.SECONDS.toMillis(viewModel.playerVideoData.value!!.duration.toLong()))
            it.prepare()
            it.play()
        }



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video