How to show ads at specific points using ExoPlayer

2020-06-30 03:30发布

问题:

I am using ExoPlayer 2.7.3 with IMA extension. I have to show ads at certain intervals. I have managed to integrate the AdsLoader and AdsMediaSource. I am receiving and displaying the ads. But the ads are only appearing at the beginning of the movie. How do I make the ads to be shown at the points when I want them to (for eg. at every 30 minutes)?

回答1:

I'm not sure whether you are using the IMA extension with the ImaAdsLoader or your custom implementation of AdsLoader which is part of the core library (no IMA extension required):

Using IMA ad tags

If you are using the IMA extension you need to create an the ImaAdsLoader with an ad tag from IMA/DoubleClick (sample tags):

new ImaAdsLoader(this, adTagUri);

The tag points to a VMAP/VAST file which defines when the ads are played. So with this solution you can't tell the player the position of the ads programmatically. Instead all this information is loaded from the ad tag.

Custom AdsLoader implementation

You can create your own implementation of AdsLoader which you can pass to the constructor or the AdsMediaSource instead of the IMA version. The AdsMediaSource will then call the attachPlayer(player, eventListener, adUiViewGroup) method of your ads loader. The second param is an AdsLoader.EventListener with which the AdsMediaSource can be notified about the state of your ads loader.

If, at this moment, you already have the information of the ads and at what position to play them, you can just call the listener once when the player is attached:

    // create playback state with two ad groups (at 0 and 30 seconds)
    AdPlaybackState adPlaybackState = new AdPlaybackState(0, 30 * C.MICROS_PER_SECOND);
    // add the uri of the first ad of the first ad group
    adPlaybackState = adPlaybackState.withAdUri(0, 0, mp4UriWithAd);
    // add the uri of the first ad of the second ad group
    adPlaybackState = adPlaybackState.withAdUri(1, 0, mp4UriWithAd);
    // add the uri of the second ad of the second ad group
    adPlaybackState = adPlaybackState.withAdUri(1, 1, mp4UriWithAd);
    // pass to AdsLoader.EventListener 
    eventListener.onAdPlaybackState(adPlaybackState);

However, it might happen that you need to load ad information from the network first. In this case you can just update the playback state when ever you retrieved new information about ads. Just call onAdPlaybackState again for an update.