Pierwsze kroki z rozszerzeniem ExoPlayer IMA

ExoPlayer to odtwarzacz multimediów na Androida. Z tego przewodnika dowiesz się, jak korzystać z rozszerzenia ExoPlayer IMA. To rozszerzenie używa pakietu IMA DAI SDK do wysyłania żądań i odtwarzania strumieni multimediów z reklamami i treściami.

Poniżej znajdziesz listę korzyści tego rozszerzenia:

  • Upraszcza kod potrzebny do integracji funkcji IMA.
  • Skraca czas potrzebny na aktualizację do nowych wersji IMA.

Rozszerzenie ExoPlayer IMA obsługuje protokoły strumieniowania HLS i DASH. Oto podsumowanie:

Obsługa strumieni w rozszerzeniu ExoPlayer-IMA
Transmisja na żywo Strumienie VOD
HLS Znacznik wyboru Znacznik wyboru
DASH Znacznik wyboru Znacznik wyboru

Rozszerzenie ExoPlayer-IMA w wersji 1.1.0 i nowszych obsługuje transmisje na żywo DASH.

W tym przewodniku korzystamy z przewodnika ExoPlayer aby pomóc Ci utworzyć pełną aplikację i zintegrować rozszerzenie. Kompletną przykładową aplikację znajdziesz w ExoPlayerExample w GitHubie.

Wymagania wstępne

Tworzenie nowego projektu w Android Studio

Aby utworzyć projekt w Android Studio:

  1. Uruchom Android Studio.
  2. Kliknij Start a new Android Studio project (Rozpocznij nowy projekt w Android Studio).
  3. Na stronie Choose your project (Wybierz projekt) wybierz szablon No Activity (Brak aktywności).
  4. Kliknij Next (Dalej).
  5. Na stronie Configure your project (Skonfiguruj projekt) nadaj projektowi nazwę i wybierz Java jako język. Uwaga: pakiet IMA DAI SDK działa z Kotlinem, ale w tym przewodniku używamy przykładów w Javie.
  • Kliknij Finish (Zakończ).

Dodawanie rozszerzenia ExoPlayer IMA do projektu

Aby dodać rozszerzenie ExoPlayer IMA:

  1. Dodaj te importy do sekcji dependencies w pliku build.gradle aplikacji:

    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. Dodaj uprawnienia użytkownika, których pakiet IMA DAI SDK potrzebuje do wysyłania żądań reklam:

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

Konfigurowanie interfejsu ExoPlayera

Aby skonfigurować interfejs ExoPlayera:

  1. Utwórz obiekt PlayerView dla ExoPlayera.

  2. Zmień widok androidx.constraintlayout.widget.ConstraintLayout na widok LinearLayout, zgodnie z zaleceniami rozszerzenia 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>
    
    

Dodawanie parametrów strumienia

Przykładowe zasoby strumienia do testowania projektu znajdziesz na stronie przykładowego strumienia IMA. Aby skonfigurować własne strumienie, zapoznaj się z sekcją Ad Manager dotyczącą DAI.

Ten krok konfiguruje transmisję na żywo. Rozszerzenie ExoPlayer IMA obsługuje też strumienie DAI VOD. Aby dowiedzieć się, jakie zmiany musisz wprowadzić w aplikacji w przypadku strumieni VOD, zapoznaj się z krokiem dotyczącym strumieni wideo na żądanie (VOD).

Importowanie rozszerzenia ExoPlayer IMA

  1. Dodaj te instrukcje importu dla rozszerzenia 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. W pliku MyActivity.java dodaj te zmienne prywatne:

    Aby przetestować strumień HLS Big Buck Bunny (Live), dodaj jego klucz zasobu. Więcej strumieni do testowania znajdziesz na stronie przykładowego strumienia IMA.

  3. Utwórz stałą KEY_ADS_LOADER_STATE, aby zapisywać i pobierać stan 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;
    
    

Tworzenie instancji adsLoader

Zastąp metodę onCreate. Znajdź w niej PlayerView i sprawdź, czy jest zapisany AdsLoader.State. Możesz użyć tego stanu podczas inicjowania obiektu 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;
}

Dodawanie metod inicjowania odtwarzacza

Dodaj metodę inicjowania odtwarzacza. Ta metoda musi wykonać te czynności:

  • Utwórz instancję AdsLoader.
  • Utwórz ExoPlayer.
  • Utwórz MediaItem za pomocą klucza zasobu transmisji na żywo.
  • Ustaw MediaItem dla odtwarzacza.
// 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();
}

Dodawanie metody zwalniania odtwarzacza

Dodaj metodę zwalniania odtwarzacza. Ta metoda musi wykonać te czynności w podanej kolejności:

  • Ustaw odniesienia do odtwarzacza na null i zwolnij zasoby odtwarzacza.
  • Zwolnij stan 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();
}

Obsługa zdarzeń odtwarzacza

Aby obsługiwać zdarzenia odtwarzacza, utwórz wywołania zwrotne dla zdarzeń cyklu życia aktywności, aby zarządzać odtwarzaniem strumienia.

W przypadku Androida w wersji 24 lub nowszej użyj tych metod:

W przypadku Androida w wersji starszej niż 24 użyj tych metod:

Metody onStart() i onResume() są mapowane na playerView.onResume(), a metody onStop() i onPause() na playerView.onPause().

Ten krok używa też zdarzenia onSaveInstanceState() do zapisywania 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());
  }
}

Konfigurowanie strumienia VOD (opcjonalnie)

Jeśli Twoja aplikacja musi odtwarzać treści VOD z reklamami, wykonaj te czynności:

  1. Dodaj CMS ID i Video ID dla strumienia VOD. Do testowania użyj tych parametrów strumienia:
    • CMS ID: "2548831"
    • Video ID: "tears-of-steel"
  2. Utwórz identyfikator URI SSAI VOD za pomocą metody 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. Ustaw nowy identyfikator URI strumienia VOD jako element multimedialny odtwarzacza za pomocą metody MediaItem.fromUri().

Jeśli operacja się powiedzie, możesz wysyłać żądania i odtwarzać strumień multimediów za pomocą rozszerzenia ExoPlayer IMA. Pełny przykład znajdziesz w repozytorium Android DAI samples w GitHubie.