ExoPlayer IMA 扩展程序使用入门

ExoPlayer 是一款 Android 媒体播放器。本指南介绍了如何使用 ExoPlayer IMA 扩展程序。此扩展程序使用 IMA DAI SDK 请求和播放包含广告和内容的媒体流。

以下列出了该扩展程序的优势:

  • 简化了集成 IMA 功能所需的代码。
  • 缩短更新到新 IMA 版本所需的时间。

ExoPlayer IMA 扩展程序支持 HLS 和 DASH 流式传输协议。总结如下:

ExoPlayer-IMA 扩展程序流支持
直播 VOD 串流
HLS 对勾标记 对勾标记
DASH 对勾标记 对勾标记

ExoPlayer-IMA 1.1.0 及更高版本支持 DASH 直播。

本指南将使用 ExoPlayer 指南来帮助您创建完整应用并集成扩展程序。如需查看完整的示例应用,请参阅 GitHub 上的 ExoPlayerExample

前提条件

创建新的 Android Studio 项目

如需创建 Android Studio 项目,请按以下步骤操作:

  1. 启动 Android Studio。
  2. 选择 Start a new Android Studio project
  3. Choose your project 页面上,选择 No Activity 模板。
  4. 点击下一步
  5. 配置项目页面上,为项目命名,然后选择 Java 作为语言。 注意:IMA DAI SDK 可与 Kotlin 搭配使用,但本指南使用 Java 示例。
  • 点击完成

将 ExoPlayer IMA 扩展程序添加到项目中

如需添加 ExoPlayer IMA 扩展程序,请执行以下操作:

  1. 在应用的 build.gradle 文件的 dependencies 部分中添加以下导入内容:

    dependencies {
        def media3_version = "1.8.0"
        implementation(platform("org.jetbrains.kotlin:kotlin-bom:1.8.0"))
        implementation 'androidx.appcompat:appcompat:1.7.1'
        implementation "androidx.media3:media3-ui:$media3_version"
        implementation "androidx.media3:media3-exoplayer:$media3_version"
        implementation "androidx.media3:media3-exoplayer-hls:$media3_version"
        implementation "androidx.media3:media3-exoplayer-dash:$media3_version"
    
        // The library adds the IMA ExoPlayer integration for ads.
        implementation "androidx.media3:media3-exoplayer-ima:$media3_version"
    }
    
  2. 添加 IMA DAI SDK 请求广告所需的用户权限:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    

设置 ExoPlayer 界面

如需设置 ExoPlayer 界面,请执行以下操作:

  1. 为 ExoPlayer 创建 PlayerView 对象。

  2. androidx.constraintlayout.widget.ConstraintLayout 视图更改为 LinearLayout 视图,如 ExoPlayer IMA 扩展程序建议的那样:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MyActivity"
        tools:ignore="MergeRootFrame">
    
        <androidx.media3.ui.PlayerView
            android:id="@+id/player_view"
            android:fitsSystemWindows="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
        <!-- UI element for viewing SDK event log -->
        <TextView
            android:id="@+id/logText"
            android:gravity="bottom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLines="100"
            android:scrollbars="vertical"
            android:textSize="@dimen/font_size">
        </TextView>
    
    </LinearLayout>
    
    

添加直播参数

如需用于测试项目的示例流媒体资源,请参阅 IMA 示例流媒体页面。如需设置您自己的流,请参阅 Ad Manager 中有关 DAI 的部分

此步骤用于设置直播。ExoPlayer IMA 扩展程序还支持 DAI VOD 视频流。如需了解您的应用需要做出哪些更改才能支持视频点播 (VOD) 流,请参阅视频点播 (VOD) 流的步骤

导入 ExoPlayer IMA 扩展程序

  1. 为 ExoPlayer 扩展程序添加以下 import 语句:

    import static androidx.media3.common.C.CONTENT_TYPE_HLS;
    
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.net.Uri;
    import android.os.Bundle;
    import android.text.method.ScrollingMovementMethod;
    import android.util.Log;
    import android.widget.TextView;
    import androidx.media3.common.MediaItem;
    import androidx.media3.common.util.Util;
    import androidx.media3.datasource.DataSource;
    import androidx.media3.datasource.DefaultDataSource;
    import androidx.media3.exoplayer.ExoPlayer;
    import androidx.media3.exoplayer.ima.ImaServerSideAdInsertionMediaSource;
    import androidx.media3.exoplayer.ima.ImaServerSideAdInsertionUriBuilder;
    import androidx.media3.exoplayer.source.DefaultMediaSourceFactory;
    import androidx.media3.ui.PlayerView;
    import com.google.ads.interactivemedia.v3.api.AdEvent;
    import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
    import com.google.ads.interactivemedia.v3.api.ImaSdkSettings;
    import java.util.HashMap;
    import java.util.Map;
    
    
  2. MyActivity.java 中,添加以下私有变量:

    如需使用 Big Buck Bunny (Live) HLS 视频流进行测试,请添加其素材资源键。 您可以在 IMA 的示例视频流页面上找到更多用于测试的视频流。

  3. 创建一个 KEY_ADS_LOADER_STATE 常量来保存和检索 AdsLoader 状态:

    /** Main Activity. */
    @SuppressLint("UnsafeOptInUsageError")
    /* @SuppressLint is needed for new media3 APIs. */
    public class MyActivity extends Activity {
    
      private static final String KEY_ADS_LOADER_STATE = "ads_loader_state";
      private static final String SAMPLE_ASSET_KEY = "c-rArva4ShKVIAkNfy6HUQ";
      private static final String LOG_TAG = "ImaExoPlayerExample";
    
      private PlayerView playerView;
      private TextView logText;
      private ExoPlayer player;
      private ImaServerSideAdInsertionMediaSource.AdsLoader adsLoader;
      private ImaServerSideAdInsertionMediaSource.AdsLoader.State adsLoaderState;
      private ImaSdkSettings imaSdkSettings;
    
    

创建 adsLoader 实例

替换 onCreate 方法。在其中找到 PlayerView,并检查是否有已保存的 AdsLoader.State。 您可以在初始化 adsLoader 对象时使用此状态。

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_my);

  // Initialize the IMA SDK as early as possible when the app starts. If your app already
  // overrides Application.onCreate(), call this method inside the onCreate() method.
  // https://developer.android.com/topic/performance/vitals/launch-time#app-creation
  ImaSdkFactory.getInstance().initialize(this, getImaSdkSettings());

  playerView = findViewById(R.id.player_view);

  // Checks if there is a saved AdsLoader state to be used later when initiating the AdsLoader.
  if (savedInstanceState != null) {
    Bundle adsLoaderStateBundle = savedInstanceState.getBundle(KEY_ADS_LOADER_STATE);
    if (adsLoaderStateBundle != null) {
      adsLoaderState =
          ImaServerSideAdInsertionMediaSource.AdsLoader.State.fromBundle(adsLoaderStateBundle);
    }
  }
}

private ImaSdkSettings getImaSdkSettings() {
  if (imaSdkSettings == null) {
    imaSdkSettings = ImaSdkFactory.getInstance().createImaSdkSettings();
    // Set any IMA SDK settings here.
  }
  return imaSdkSettings;
}

添加了用于初始化播放器的方法

添加了一种初始化播放器的方法。此方法必须执行以下操作:

  • 创建一个 AdsLoader 实例。
  • 创建 ExoPlayer
  • 使用直播的素材资源键创建 MediaItem
  • 为播放器设置 MediaItem
// Create a server side ad insertion (SSAI) AdsLoader.
private ImaServerSideAdInsertionMediaSource.AdsLoader createAdsLoader() {
  ImaServerSideAdInsertionMediaSource.AdsLoader.Builder adsLoaderBuilder =
      new ImaServerSideAdInsertionMediaSource.AdsLoader.Builder(this, playerView);

  // Attempts to set the AdsLoader state if available from a previous session.
  if (adsLoaderState != null) {
    adsLoaderBuilder.setAdsLoaderState(adsLoaderState);
  }

  return adsLoaderBuilder
      .setAdEventListener(buildAdEventListener())
      .setImaSdkSettings(getImaSdkSettings())
      .build();
}

private void initializePlayer() {
  adsLoader = createAdsLoader();

  // Set up the factory for media sources, passing the ads loader.
  DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(this);

  DefaultMediaSourceFactory mediaSourceFactory = new DefaultMediaSourceFactory(dataSourceFactory);

  // MediaSource.Factory to create the ad sources for the current player.
  ImaServerSideAdInsertionMediaSource.Factory adsMediaSourceFactory =
      new ImaServerSideAdInsertionMediaSource.Factory(adsLoader, mediaSourceFactory);

  // 'mediaSourceFactory' is an ExoPlayer component for the DefaultMediaSourceFactory.
  // 'adsMediaSourceFactory' is an ExoPlayer component for a MediaSource factory for IMA server
  // side inserted ad streams.
  mediaSourceFactory.setServerSideAdInsertionMediaSourceFactory(adsMediaSourceFactory);

  // Create a SimpleExoPlayer and set it as the player for content and ads.
  player = new ExoPlayer.Builder(this).setMediaSourceFactory(mediaSourceFactory).build();
  playerView.setPlayer(player);
  adsLoader.setPlayer(player);

  // Create the MediaItem to play, specifying the stream URI.
  Uri ssaiUri = buildLiveStreamUri(SAMPLE_ASSET_KEY, CONTENT_TYPE_HLS);
  MediaItem ssaiMediaItem = MediaItem.fromUri(ssaiUri);

  // Prepare the content and ad to be played with the ExoPlayer.
  player.setMediaItem(ssaiMediaItem);
  player.prepare();

  // Set PlayWhenReady. If true, content and ads will autoplay.
  player.setPlayWhenReady(false);
}

/**
 * Builds an IMA SSAI live stream URI for the given asset key and format.
 *
 * @param assetKey The asset key of the live stream.
 * @param format The format of the live stream request, either {@code CONTENT_TYPE_HLS} or {@code
 *     CONTENT_TYPE_DASH}.
 * @return The URI of the live stream.
 */
public Uri buildLiveStreamUri(String assetKey, int format) {
  Map<String, String> adTagParams = new HashMap<String, String>();
  // Update the adTagParams map with any parameters.
  // For more information, see https://support.google.com/admanager/answer/7320899

  return new ImaServerSideAdInsertionUriBuilder()
      .setAssetKey(assetKey)
      .setFormat(format)
      .setAdTagParameters(adTagParams)
      .build();
}

添加了释放播放器的方法

添加了释放播放器的方法。此方法必须按顺序执行以下操作:

  • 将播放器引用设置为 null 并释放播放器的资源。
  • 释放 adsLoader 状态。
private void releasePlayer() {
  // Set the player references to null and release the player's resources.
  playerView.setPlayer(null);
  player.release();
  player = null;

  // Release the adsLoader state so that it can be initiated again.
  adsLoaderState = adsLoader.release();
}

处理播放器事件

如需处理播放器事件,请为 activity 的生命周期事件创建回调,以管理视频流播放。

对于 Android API 级别 24 及更高级别,请使用以下方法:

对于低于 24 的 Android API 级别,请使用以下方法:

onStart()onResume() 方法映射到 playerView.onResume(),而 onStop()onPause() 映射到 playerView.onPause()

此步骤还使用 onSaveInstanceState() 事件来保存 adsLoaderState

@Override
public void onStart() {
  super.onStart();
  if (Util.SDK_INT > 23) {
    initializePlayer();
    if (playerView != null) {
      playerView.onResume();
    }
  }
}

@Override
public void onResume() {
  super.onResume();
  if (Util.SDK_INT <= 23 || player == null) {
    initializePlayer();
    if (playerView != null) {
      playerView.onResume();
    }
  }
}

@Override
public void onPause() {
  super.onPause();
  if (Util.SDK_INT <= 23) {
    if (playerView != null) {
      playerView.onPause();
    }
    releasePlayer();
  }
}

@Override
public void onStop() {
  super.onStop();
  if (Util.SDK_INT > 23) {
    if (playerView != null) {
      playerView.onPause();
    }
    releasePlayer();
  }
}

@Override
public void onSaveInstanceState(Bundle outState) {
  // Attempts to save the AdsLoader state to handle app backgrounding.
  if (adsLoaderState != null) {
    outState.putBundle(KEY_ADS_LOADER_STATE, adsLoaderState.toBundle());
  }
}

VOD 视频流设置(可选)

如果您的应用需要播放包含广告的 VOD 内容,请按以下步骤操作:

  1. 为 VOD 视频流添加了 CMS IDVideo ID。 对于测试,请使用以下视频流参数:
    • CMS ID"2548831"
    • 视频 ID"tears-of-steel"
  2. 使用 ImaServerSideAdInsertionUriBuilder() 方法创建 SSAI VOD URI:

    /**
     * Builds an IMA SSAI VOD stream URI for the given CMS ID, video ID, and format.
     *
     * @param cmsId The CMS ID of the VOD stream.
     * @param videoId The video ID of the VOD stream.
     * @param format The format of the VOD stream request, either {@code CONTENT_TYPE_HLS} or {@code
     *     CONTENT_TYPE_DASH}.
     * @return The URI of the VOD stream.
     */
    public Uri buildVodStreamUri(String cmsId, String videoId, int format) {
      Map<String, String> adTagParams = new HashMap<String, String>();
      // Update the adTagParams map with any parameters.
      // For more information, see https://support.google.com/admanager/answer/7320899
    
      return new ImaServerSideAdInsertionUriBuilder()
          .setContentSourceId(cmsId)
          .setVideoId(videoId)
          .setFormat(format)
          .setAdTagParameters(adTagParams)
          .build();
    }
    
    
  3. 使用 MediaItem.fromUri() 方法将新的 VOD 流 URI 设置为播放器的媒体项。

如果成功,您可以使用 ExoPlayer IMA 扩展程序请求和播放媒体流。如需查看完整示例,请参阅 GitHub 上的 Android DAI 示例