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

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

ตัวอย่างประโยชน์ของส่วนขยายมีดังนี้

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

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

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

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

คู่มือนี้อิงตามคู่มือ ExoPlayer และแสดงวิธีสร้างแอปแบบเต็มและผสานรวมส่วนขยาย ดูExoPlayerExampleจาก GitHub เพื่อดูตัวอย่างที่มี แอปตัวอย่างที่สมบูรณ์

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

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

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

  • เริ่มใช้ Android Studio
  • เลือก Start a new Android Studio project
  • ในหน้าเลือกโปรเจ็กต์ ให้เลือกเทมเพลตไม่มีกิจกรรม
  • คลิกถัดไป
  • ในหน้า Configure your project ให้ตั้งชื่อโปรเจ็กต์และเลือก Java เป็นภาษา

  • คลิกเสร็จสิ้น

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

เพิ่มการนำเข้าสำหรับส่วนขยายไปยังไฟล์ build.gradle ระดับแอปพลิเคชัน ในส่วน dependencies

กำหนดค่าแอปและเปิดใช้ multidex การดำเนินการนี้จำเป็นเนื่องจากขนาดของส่วนขยาย และจำเป็นสำหรับแอปที่ตั้งค่า minSdkVersion เป็น Android 4.4W (API ระดับ 20) หรือต่ำกว่า

เช่น

app/build.gradle

android {

  ...

  defaultConfig {
      applicationId "com.google.ads.interactivemedia.v3.samples.videoplayerapp"
      minSdkVersion 21
      targetSdkVersion 34
      multiDexEnabled true
      versionCode 1
      versionName "1.0"
  }

    ...
}
dependencies {
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'androidx.media3:media3-ui:1.7.1'
    implementation 'androidx.media3:media3-exoplayer:1.7.1'
    implementation 'androidx.media3:media3-exoplayer-hls:1.7.1'
    implementation 'androidx.media3:media3-exoplayer-dash:1.7.1'

    // Adding the ExoPlayer IMA extension for ads will also include the IMA
    // SDK as a dependency.
    implementation 'androidx.media3:media3-exoplayer-ima:1.7.1'
}

เพิ่มสิทธิ์ของผู้ใช้ที่ IMA DAI SDK กำหนดสำหรับการขอโฆษณา

app/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.project name">

    <!-- Required permissions for the IMA DAI SDK -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    ...

</manifest>

เพิ่มการประกาศความตั้งใจ

หากแอปกำหนดเป้าหมายเป็น Android 11 (API ระดับ 30) ขึ้นไป IMA DAI SDK เวอร์ชันปัจจุบันและเวอร์ชันล่าสุด กำหนดให้ต้องประกาศความตั้งใจที่จะเปิดลิงก์บนเว็บอย่างชัดเจน เพิ่มข้อมูลโค้ดต่อไปนี้ลงในไฟล์ Manifest ของแอปเพื่อ เปิดใช้การคลิกผ่านโฆษณา (ผู้ใช้คลิกปุ่มดูข้อมูลเพิ่มเติม)

  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.project name">

      ...

    </application>

    <queries>
      <intent>
          <action android:name="android.intent.action.VIEW" />
          <data android:scheme="https" />
      </intent>
      <intent>
          <action android:name="android.intent.action.VIEW" />
          <data android:scheme="http" />
      </intent>
    </queries>
  </manifest>

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

สร้างออบเจ็กต์ PlayerView เพื่อให้ ExoPlayer ใช้

เปลี่ยน androidx.constraintlayout.widget.ConstraintLayout เป็น LinearLayout ซึ่งเป็นค่าที่แนะนำสำหรับส่วนขยาย IMA ของ ExoPlayer

เช่น

app/src/main/res/layout/activity_my.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@android:color/black"
    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:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

เพิ่มพารามิเตอร์ของสตรีม

ดูหน้าสตรีมตัวอย่าง IMA เพื่อดูชิ้นงานสตรีมตัวอย่าง สำหรับทดสอบโปรเจ็กต์ นอกจากนี้ โปรดดูส่วน Ad Manager ใน DAI เพื่อดูข้อมูลเกี่ยวกับการตั้งค่าสตรีมของคุณเอง

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

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

เพิ่มคำสั่งนำเข้าสำหรับส่วนขยาย ExoPlayer

เพิ่มตัวแปรส่วนตัวต่อไปนี้ลงใน MyActivity.java

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

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

เช่น

app/src/main/java/com/example/project name/MyActivity.java


import static androidx.media3.common.C.CONTENT_TYPE_HLS;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.OptIn;
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.exoplayer.util.EventLogger;
import androidx.media3.ui.PlayerView;
import androidx.multidex.MultiDex;
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
import com.google.ads.interactivemedia.v3.api.ImaSdkSettings;

...

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 PlayerView playerView;
  private ExoPlayer player;
  private ImaSdkSettings imaSdkSettings;
  private ImaServerSideAdInsertionMediaSource.AdsLoader adsLoader;
  private ImaServerSideAdInsertionMediaSource.AdsLoader.State adsLoaderState;

}

สร้างอินสแตนซ์ adsLoader

เขียนทับเมธอด onCreate เพื่อค้นหา PlayerView และตรวจสอบว่ามี AdsLoader.State ที่บันทึกไว้หรือไม่ ซึ่งจะใช้ได้เมื่อเริ่มต้นออบเจ็กต์ adsLoader

นอกจากนี้ ให้เปิดใช้ Multidex หากจำนวนเมธอดของแอปและ minSdkVersion (ตามที่อธิบายไว้ในขั้นตอนที่ 2) กำหนดให้ทำ

เช่น

app/src/main/java/com/example/project name/MyActivity.java

...

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 PlayerView playerView;
  private ExoPlayer player;
  private ImaSdkSettings imaSdkSettings;
  private ImaServerSideAdInsertionMediaSource.AdsLoader adsLoader;
  private ImaServerSideAdInsertionMediaSource.AdsLoader.State adsLoaderState;

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

    // 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 ให้กับเพลเยอร์

เช่น

app/src/main/java/com/example/project name/MyActivity.java

public class MyActivity extends Activity {

  ...

  
  // Create a server side ad insertion (SSAI) AdsLoader.
  private ImaServerSideAdInsertionMediaSource.AdsLoader createAdsLoader() {
    ImaServerSideAdInsertionMediaSource.AdsLoader.Builder adsLoaderBuilder =
        new ImaServerSideAdInsertionMediaSource.AdsLoader.Builder(this, playerView);

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

    return adsLoaderBuilder
        .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 an ExoPlayer and set it as the player for content and ads.
    player = new ExoPlayer.Builder(this).setMediaSourceFactory(mediaSourceFactory).build();
    playerView.setPlayer(player);
    adsLoader.setPlayer(player);

    // Build an IMA SSAI media item to prepare the player with.
    Uri ssaiLiveUri =
        new ImaServerSideAdInsertionUriBuilder()
            .setAssetKey(SAMPLE_ASSET_KEY)
            .setFormat(CONTENT_TYPE_HLS) // Use CONTENT_TYPE_DASH for dash streams.
            .build();

    // Create the MediaItem to play, specifying the stream URI.
    MediaItem ssaiMediaItem = MediaItem.fromUri(ssaiLiveUri);

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

เพิ่มวิธีการปล่อยตัวผู้เล่น

เพิ่มวิธีการปล่อยตัวผู้เล่นในลำดับนี้

  • ตั้งค่าการอ้างอิงเพลเยอร์เป็น null และปล่อยทรัพยากรของเพลเยอร์
  • ปล่อยสถานะของ adsLoader

app/src/main/java/com/example/project name/MyActivity.java

public class MyActivity extends Activity {

  ...

  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 SDK เวอร์ชัน 24 ขึ้นไป ให้ทำดังนี้

หากต้องการรองรับ Android SDK เวอร์ชันที่ต่ำกว่า 24 ให้ทำดังนี้

onStart() และ onResume() แมปกับ playerView.onResume() และ onStop() และ onPause() แมปกับ playerView.onPause()

ขั้นตอนนี้ยังใช้เหตุการณ์ onSaveInstanceState() เพื่อพยายามบันทึก adsLoaderState ด้วย

app/src/main/java/com/example/project name/MyActivity.java

public class MyActivity extends Activity {

  ...

  @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
  2. สร้าง URI ของ VOD สำหรับ SSAI โดยใช้ ImaServerSideAdInsertionUriBuilder()
  3. ใช้ URI ใหม่นี้เป็นรายการสื่อของเพลเยอร์

app/src/main/java/com/example/project name/MyActivity.java

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 SAMPLE_CMS_ID = "2548831";
  private static final String SAMPLE_VIDEO_ID = "tears-of-steel";

  ...

  private void initializePlayer() {

     ...

    Uri ssaiVodUri =
        new ImaServerSideAdInsertionUriBuilder()
            .setContentSourceId(SAMPLE_CMS_ID)
            .setVideoId(SAMPLE_VIDEO_ID)
            .setFormat(CONTENT_TYPE_HLS)
            .build();

    // Create the MediaItem to play, specifying the stream URI.
    MediaItem ssaiMediaItem = MediaItem.fromUri(ssaiVodUri);

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

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