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

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 เพื่อช่วยคุณสร้างแอปแบบเต็มและผสานรวมส่วนขยาย หากต้องการดูแอปตัวอย่างแบบเต็ม โปรดดู ExoPlayerExample ใน GitHub

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

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

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

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

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

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

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

    dependencies {
        def media3_version = "1.9.1"
        coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")
        implementation(platform("org.jetbrains.kotlin:kotlin-bom:2.3.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 ตามที่ส่วนขยาย 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 ยังรองรับสตรีม VOD ของ DAI ด้วย หากต้องการดูการเปลี่ยนแปลงที่แอปต้องใช้สำหรับสตรีม VOD, โปรดดู ขั้นตอนสำหรับสตรีมวิดีโอออนดีมานด์ (VOD)

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

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

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

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

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

สำหรับ Android API ระดับต่ำกว่า 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 ID: "2548831"
    • Video ID: "tears-of-steel"
  2. สร้าง URI ของ SSAI VOD โดยใช้เมธอด 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()

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