เริ่มต้นใช้งานส่วนขยาย IMA ของ ExoPlayer

ExoPlayer เป็นโปรแกรมเล่นสื่อของ Android คู่มือนี้จะแสดงวิธีใช้ส่วนขยาย IMA ของ ExoPlayer ส่วนขยายนี้ใช้ IMA DAI SDK เพื่อขอและเล่นสตรีมสื่อที่มีทั้งโฆษณาและเนื้อหา

รายการต่อไปนี้แสดงประโยชน์ของส่วนขยาย

  • ลดความซับซ้อนของโค้ดที่จำเป็นต่อการผสานรวมฟีเจอร์ IMA
  • ลดเวลาที่ต้องใช้ในการอัปเดตเป็น IMA เวอร์ชันใหม่

ส่วนขยาย IMA ของ ExoPlayer รองรับโปรโตคอลการสตรีม HLS และ DASH สรุปมีดังนี้

การรองรับสตรีมส่วนขยาย ExoPlayer-IMA
ไลฟ์สด สตรีม VOD
HLS เครื่องหมายถูก เครื่องหมายถูก
DASH เครื่องหมายถูก เครื่องหมายถูก

ExoPlayer-IMA เวอร์ชัน 1.1.0 ขึ้นไปรองรับสตรีมแบบสด DASH

คู่มือนี้ใช้ คู่มือ ExoPlayer เพื่อช่วยคุณสร้างแอปแบบเต็มและผสานรวมส่วนขยาย ดูแอปตัวอย่างฉบับสมบูรณ์ได้ที่ ExoPlayerExample ใน GitHub

ข้อกำหนดเบื้องต้น

สร้างโปรเจ็กต์ Android Studio ใหม่

หากต้องการสร้างโปรเจ็กต์ Android Studio ให้ทำตามขั้นตอนต่อไปนี้

  1. เริ่มใช้ Android Studio
  2. เลือก Start a new Android Studio project
  3. ในหน้าเลือกโปรเจ็กต์ ให้เลือกเทมเพลตไม่มีกิจกรรม
  4. คลิกถัดไป
  5. ในหน้ากำหนดค่าโปรเจ็กต์ ให้ตั้งชื่อโปรเจ็กต์และเลือก Java เป็นภาษา หมายเหตุ: IMA DAI SDK ทำงานร่วมกับ Kotlin ได้ แต่คู่มือนี้ใช้ตัวอย่าง Java
  • คลิกเสร็จสิ้น

เพิ่มส่วนขยาย IMA ของ ExoPlayer ลงในโปรเจ็กต์

หากต้องการเพิ่มส่วนขยาย IMA ของ ExoPlayer ให้ทำดังนี้

  1. รวมการนำเข้าต่อไปนี้ในส่วน dependencies ของไฟล์ build.gradle ของแอป

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

ตั้งค่า UI ของ ExoPlayer

หากต้องการตั้งค่า UI ของ ExoPlayer ให้ทำดังนี้

  1. สร้างออบเจ็กต์ PlayerView สำหรับ ExoPlayer

  2. เปลี่ยนandroidx.constraintlayout.widget.ConstraintLayoutเป็นLinearLayoutตามที่ส่วนขยาย IMA ของ ExoPlayer แนะนำ

    <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

ขั้นตอนนี้จะตั้งค่าไลฟ์สด ส่วนขยาย IMA ของ ExoPlayer ยัง รองรับสตรีม VOD ของ DAI ด้วย หากต้องการดูว่าแอปของคุณต้องเปลี่ยนแปลงอะไรบ้างสำหรับสตรีม VOD โปรดดูขั้นตอนสำหรับสตรีมวิดีโอออนดีมานด์ (VOD)

นำเข้าส่วนขยาย IMA ของ ExoPlayer

  1. เพิ่มคำสั่งนำเข้าต่อไปนี้สำหรับส่วนขยาย ExoPlayer

    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 ให้เพิ่มตัวแปรส่วนตัวต่อไปนี้

    หากต้องการทดสอบด้วยสตรีม HLS ของ Big Buck Bunny (Live) ให้เพิ่มคีย์ของชิ้นงาน คุณดูสตรีมอื่นๆ เพื่อทดสอบได้ในหน้าสตรีมตัวอย่างของ IMA

  3. สร้างค่าคงที่เพื่อบันทึกและเรียกข้อมูลสถานะ KEY_ADS_LOADER_STATEAdsLoader

    /** 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();
}

จัดการเหตุการณ์ของผู้เล่น

หากต้องการจัดการเหตุการณ์ของเพลเยอร์ ให้สร้างการเรียกกลับสำหรับเหตุการณ์วงจรของกิจกรรม เพื่อจัดการการเล่นสตรีม

สำหรับ Android API ระดับ 24 ขึ้นไป ให้ใช้วิธีการต่อไปนี้

สำหรับ API ระดับ Android ที่ต่ำกว่า 24 ให้ใช้วิธีการต่อไปนี้

เมธอด 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. เพิ่ม CMS ID และ Video ID สำหรับสตรีม VOD สำหรับการทดสอบ ให้ใช้พารามิเตอร์สตรีมต่อไปนี้
    • รหัส CMS: "2548831"
    • รหัสวิดีโอ: "tears-of-steel"
  2. สร้าง URI ของ VOD สำหรับ SSAI โดยใช้เมธอด ImaServerSideAdInsertionUriBuilder() ดังนี้

    /**
     * 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. ตั้งค่า URI ของสตรีม VOD ใหม่เป็นรายการสื่อของเพลเยอร์โดยใช้เมธอด MediaItem.fromUri()

หากสำเร็จ คุณจะขอและเล่นสตรีมสื่อด้วยส่วนขยาย IMA ของ ExoPlayer ได้ ดูตัวอย่างฉบับสมบูรณ์ได้ที่ตัวอย่าง DAI ของ Android ใน GitHub