開始使用 IMA DAI SDK

Stay organized with collections Save and categorize content based on your preferences.

IMA SDK 可讓您輕鬆將多媒體廣告整合至網站和應用程式中。IMA SDK 可以向任何符合 VAST 規定的廣告伺服器請求廣告,並管理應用程式中的廣告播放作業。使用 IMA DAI SDK,應用程式可對廣告和內容影片 (即 VOD 或直播內容) 提出串流請求。接著,SDK 會傳回合併的影片串流,這樣您就不必在應用程式中切換廣告和內容影片的切換。

本指南說明如何將 IMA SDK 整合到簡易的影片播放器應用程式中。如想查看已完成的流程,或按照已完成的範例整合進行,請從 GitHub 下載 BasicExample

IMA DAI 總覽

導入 IMA DAI 包含四個主要 SDK 元件,本指南會說明:

  • StreamDisplayContainer: 位於影片播放元素上方且包含廣告 UI 元素的容器物件。
  • AdsLoader:這個物件會要求串流,並處理由串流要求回應物件觸發的事件。您應該只將一個廣告載入器執行個體化,以便在應用程式的整個生命週期中重複使用。
  • StreamRequest:定義串流要求的物件。串流要求可以是隨選影片或直播。要求會指定內容 ID、API 金鑰或驗證權杖和其他參數。
  • StreamManager: 可處理動態廣告插播串流,以及與 DAI 後端互動的物件。串流管理員也會處理追蹤連線偵測 (ping),並將串流和廣告事件轉送至發布商。

必要條件

下載並執行影片播放器應用程式範例

範例應用程式提供的影片播放器可播放 HLS 影片。要以此作為整合 IMA Android SDK 動態廣告插播功能的功能。

  1. 下載範例影片播放器應用程式並解壓縮。
  2. 啟動 Android Studio 並選取「Open an existing Android Studio project」(開啟現有 Android Studio 專案);如果 Android Studio 已在執行中,則依序選取 [File] (檔案) > [New] (新增) > [Import Project] (匯入專案)。然後選擇 SampleVideoPlayer/build.gradle
  3. 依序選取 [Tools] (工具) > [Android] > [Sync Project with Gradle Files] (使用 Gradle 檔案同步處理專案) 以執行 Gradle 同步處理。
  4. 請確保玩家應用程式使用 [執行] > [執行應用程式],在實體 Android 裝置或 Android 虛擬裝置上編譯及執行。影片串流播放完畢之後,系統可能需要一段時間才能載入影片。

檢查影片播放器範例

範例影片播放器尚未包含任何 IMA SDK 整合程式碼。範例應用程式包含兩個主要部分:

  • samplevideoplayer/SampleVideoPlayer.java - 以 ExoPlayer 為基礎的簡易 HLS 播放器,做為 IMA DAI 整合的基礎。
  • videoplayerapp/MyActivity.java - 此活動會建立影片播放器,並向其傳遞 ContextSimpleExoPlayerView

在播放器應用程式中加入 IMA Android SDK

您還必須加入 IMA SDK 的參照。在 Android Studio 中,將以下內容新增至應用程式層級的 build.gradle 檔案 (位於 app/build.gradle):

repositories {
  google()
  jcenter()
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.browser:browser:1.3.0'
    implementation 'com.google.android.exoplayer:exoplayer:2.18.1'
    implementation 'com.google.ads.interactivemedia.v3:interactivemedia:3.29.0'
}

查核點:應用程式應編譯並執行,但尚未新增 UI 元素或程式碼來要求及顯示廣告。

整合 IMA SDK

  1. videoplayerapp 套件 (位於 app/java/com.google.ads.interactivemedia.v3.samples/videoplayerapp/) 中建立名為 SampleAdsWrapper 的新類別,以納入現有的 SampleVideoPlayer 並新增實作 IMA 動態廣告插播 (DAI) 的邏輯。為此,您必須先建立 AdsLoader,用來向廣告伺服器請求廣告。

    videoplayerapp/SampleAdsWrapper.java

    package com.google.ads.interactivemedia.v3.samples.videoplayerapp;
    
    import android.annotation.TargetApi;
    import android.content.Context;
    import android.os.Build;
    import android.view.ViewGroup;
    import android.webkit.WebView;
    
    import com.google.ads.interactivemedia.v3.api.AdErrorEvent;
    import com.google.ads.interactivemedia.v3.api.AdEvent;
    import com.google.ads.interactivemedia.v3.api.AdsLoader;
    import com.google.ads.interactivemedia.v3.api.AdsManagerLoadedEvent;
    import com.google.ads.interactivemedia.v3.api.CuePoint;
    import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
    import com.google.ads.interactivemedia.v3.api.ImaSdkSettings;
    import com.google.ads.interactivemedia.v3.api.StreamDisplayContainer;
    import com.google.ads.interactivemedia.v3.api.StreamManager;
    import com.google.ads.interactivemedia.v3.api.StreamRequest;
    import com.google.ads.interactivemedia.v3.api.player.VideoProgressUpdate;
    import com.google.ads.interactivemedia.v3.api.player.VideoStreamPlayer;
    import com.google.ads.interactivemedia.v3.samples.samplevideoplayer.SampleVideoPlayer;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    public class SampleAdsWrapper implements AdEvent.AdEventListener,
            AdErrorEvent.AdErrorListener, AdsLoader.AdsLoadedListener {
    
        // Live stream asset key.
        private static final String TEST_ASSET_KEY = "sN_IYUG8STe1ZzhIIE_ksA";
    
        // VOD content source and video IDs.
        private static final String TEST_CONTENT_SOURCE_ID = "2528370";
        private static final String TEST_VIDEO_ID = "tears-of-steel";
    
        private static final String PLAYER_TYPE = "DAISamplePlayer";
    
        /**
         * Log interface, so you can output the log commands to the UI or similar.
         */
        public interface Logger {
            void log(String logMessage);
        }
    
        private ImaSdkFactory sdkFactory;
        private AdsLoader adsLoader;
        private StreamDisplayContainer displayContainer;
        private StreamManager streamManager;
        private List<VideoStreamPlayer.VideoStreamPlayerCallback> playerCallbacks;
    
        private SampleVideoPlayer videoPlayer;
        private Context context;
        private ViewGroup adUiContainer;
    
        private String fallbackUrl;
        private Logger logger;
    
        public SampleAdsWrapper(Context context, SampleVideoPlayer videoPlayer,
                                ViewGroup adUiContainer) {
            this.videoPlayer = videoPlayer;
            this.context = context;
            this.adUiContainer = adUiContainer;
            sdkFactory = ImaSdkFactory.getInstance();
            playerCallbacks = new ArrayList<>();
            createAdsLoader();
            displayContainer = sdkFactory.createStreamDisplayContainer(
                this.adUiContainer,
                videoStreamPlayer
            );
        }
    
        private void createAdsLoader() {
            ImaSdkSettings settings = new ImaSdkSettings();
            adsLoader = sdkFactory.createAdsLoader(context);
        }
    
        public void requestAndPlayAds() {
            adsLoader.addAdErrorListener(this);
            adsLoader.addAdsLoadedListener(this);
            adsLoader.requestStream(buildStreamRequest());
        }
    }
              
  2. buildStreamRequest() 方法新增至 AdsLoader,使其能夠向串流請求廣告。可能是含廣告的即時串流 (預設) 或隨選影片 (隨選影片),可播放預錄內容 (含廣告)。如要啟用 VOD 串流,請為直播要求加上註解,並將 VOD 串流要求取消註解。

    videoplayerapp/SampleAdsWrapper.java

    private StreamRequest buildStreamRequest() {
        VideoStreamPlayer videoStreamPlayer = createVideoStreamPlayer();
        videoPlayer.setSampleVideoPlayerCallback(
                new SampleVideoPlayer.SampleVideoPlayerCallback() {
                    @Override
                    public void onUserTextReceived(String userText) {
                        for (VideoStreamPlayer.VideoStreamPlayerCallback callback :
                                playerCallbacks) {
                            callback.onUserTextReceived(userText);
                        }
                    }
    
                    @Override
                    public void onSeek(int windowIndex, long positionMs) {
                        // See if you would seek past an ad, and if so, jump back to it.
                        long newSeekPositionMs = positionMs;
                        if (streamManager != null) {
                            CuePoint prevCuePoint  =
                                    streamManager.getPreviousCuePointForStreamTime(positionMs / 1000);
                            if (prevCuePoint != null && !prevCuePoint.isPlayed()) {
                                newSeekPositionMs = (long) (prevCuePoint.getStartTime() * 1000);
                            }
                        }
                        videoPlayer.seekTo(windowIndex, newSeekPositionMs);
                    }
    
                    @Override
                    public void onContentComplete() {
                        for (VideoStreamPlayer.VideoStreamPlayerCallback callback : playerCallbacks) {
                            callback.onContentComplete();
                        }
                    }
    
                    @Override
                    public void onPause() {
                        for (VideoStreamPlayer.VideoStreamPlayerCallback callback : playerCallbacks) {
                            callback.onPause();
                        }
                    }
    
                    @Override
                    public void onResume() {
                        for (VideoStreamPlayer.VideoStreamPlayerCallback callback : playerCallbacks) {
                            callback.onResume();
                        }
                    }
    
                    @Override
                    public void onVolumeChanged(int percentage) {
                        for (VideoStreamPlayer.VideoStreamPlayerCallback callback : playerCallbacks) {
                            callback.onVolumeChanged(percentage);
                        }
                    }
                });
    
        // Live stream request.
        StreamRequest request = sdkFactory.createLiveStreamRequest(
                TEST_ASSET_KEY, null, displayContainer);
    
        // VOD request. Comment the createLiveStreamRequest() line above and uncomment this
        // createVodStreamRequest() below to switch from a live stream to a VOD stream.
        // StreamRequest request = sdkFactory.createVodStreamRequest(TEST_CONTENT_SOURCE_ID,
        //        TEST_VIDEO_ID, null, displayContainer);
        return request;
    }
    
  3. 您也需要 VideoStreamPlayer 才能播放串流,因此必須新增 createVideoStreamPlayer() 方法,藉此建立實作 VideoStreamPlayer 的匿名類別。

    videoplayerapp/SampleAdsWrapper.java

    private VideoStreamPlayer createVideoStreamPlayer() {
        VideoStreamPlayer player = new VideoStreamPlayer() {
            @Override
            public void loadUrl(String url, List<HashMap<String, String>> subtitles) {
                videoPlayer.setStreamUrl(url);
                videoPlayer.play();
            }
    
            @Override
            public void addCallback(
                VideoStreamPlayerCallback videoStreamPlayerCallback) {
                    playerCallbacks.add(videoStreamPlayerCallback);
            }
    
            @Override
            public void removeCallback(
                VideoStreamPlayerCallback videoStreamPlayerCallback) {
                    playerCallbacks.remove(videoStreamPlayerCallback);
            }
    
            @Override
            public void onAdBreakStarted() {
                // Disable player controls.
                videoPlayer.enableControls(false);
                log("Ad Break Started\n");
            }
    
            @Override
            public void onAdBreakEnded() {
                // Re-enable player controls.
                videoPlayer.enableControls(true);
                log("Ad Break Ended\n");
            }
    
            @Override
            public VideoProgressUpdate getContentProgress() {
                return new VideoProgressUpdate(videoPlayer.getCurrentPosition(),
                        videoPlayer.getDuration());
            }
        };
        return player;
    }
    
  4. 實作必要的事件監聽器並新增錯誤處理程序的支援。

    重要須知:請注意 AdErrorListener 實作,如果廣告無法播放,就會呼叫備用網址。由於內容和廣告屬於一個串流,如果 DAI 串流發生錯誤,您必須準備好呼叫備用串流。

    videoplayerapp/SampleAdsWrapper.java

    /** AdErrorListener implementation **/
    @Override
    public void onAdError(AdErrorEvent event) {
        // play fallback URL.
        videoPlayer.setStreamUrl(fallbackUrl);
        videoPlayer.enableControls(true);
        videoPlayer.play();
    }
    
    /** AdEventListener implementation **/
    @Override
    public void onAdEvent(AdEvent event) {
        switch (event.getType()) {
            case AD_PROGRESS:
                // Do nothing or else log are filled by these messages.
                break;
            default:
                log(String.format("Event: %s\n", event.getType()));
                break;
        }
    }
    
    /** AdsLoadedListener implementation **/
    @Override
    public void onAdsManagerLoaded(AdsManagerLoadedEvent event) {
        streamManager = event.getStreamManager();
        streamManager.addAdErrorListener(this);
        streamManager.addAdEventListener(this);
        streamManager.init();
    }
    
    /** Sets fallback URL in case ads stream fails. **/
    void setFallbackUrl(String url) {
        fallbackUrl = url;
    }
    
  5. 新增用於記錄的程式碼。

    videoplayerapp/SampleAdsWrapper.java

    /** Sets logger for displaying events to screen. Optional. **/
    void setLogger(Logger logger) {
        this.logger = logger;
    }
    
    private void log(String message) {
        if (logger != null) {
            logger.log(message);
        }
    }
    
  6. 修改 videoplayerapp 中的 MyActivity,執行個體化並呼叫 SampleAdsWrapper

    videoplayerapp/MyActivity.java

    import android.view.ViewGroup;
    import android.widget.ScrollView;
    …
    public class MyActivity extends AppCompatActivity {
    …
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_my);
            View rootView = findViewById(R.id.videoLayout);
            videoPlayer = new SampleVideoPlayer(rootView.getContext(),
                    (SimpleExoPlayerView) rootView.findViewById(R.id.playerView));
            videoPlayer.enableControls(false);
    
            final SampleAdsWrapper sampleAdsWrapper = new SampleAdsWrapper(this, videoPlayer,
                (ViewGroup) rootView.findViewById(R.id.adUiContainer));
            sampleAdsWrapper.setFallbackUrl(DEFAULT_STREAM_URL);
    
            final ScrollView scrollView = (ScrollView) findViewById(R.id.logScroll);
            final TextView textView = (TextView) findViewById(R.id.logText);
    
            sampleAdsWrapper.setLogger(new SampleAdsWrapper.Logger() {
                @Override
                public void log(String logMessage) {
                    Log.i(APP_LOG_TAG, logMessage);
                    if (textView != null) {
                        textView.append(logMessage);
                    }
                    if (scrollView != null) {
                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                scrollView.fullScroll(View.FOCUS_DOWN);
                            }
                        });
                    }
                }
            });
    
            playButton = (ImageButton) rootView.findViewById(R.id.playButton);
            // Set up play button listener to play video then hide play button.
            playButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    sampleAdsWrapper.requestAndPlayAds();
                    playButton.setVisibility(View.GONE);
                }
            });
        }
    …
    }
  7. 修改活動的版面配置檔案 activity_my.xml,以新增用於記錄的 UI 元素。

    res/layout/activity_my.xml

    …
        <TextView
            android:id="@+id/playerDescription"
            android:text="@string/video_description"
            android:textAlignment="center"
            android:gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.1"
            android:textSize="@dimen/font_size" />
        <!-- UI element for viewing SDK event log -->
        <ScrollView
            android:id="@+id/logScroll"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.5"
            android:padding="5dp"
            android:background="#DDDDDD">
    
            <TextView
                android:id="@+id/logText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
            </TextView>
        </ScrollView>
    

恭喜!您現已在 Android 應用程式請求及顯示影片廣告。 如要微調您的實作項目,請參閱書籤Snapback 指南以及 API 說明文件

疑難排解

如果在播放影片廣告時出現問題,請嘗試下載完整的 BasicExample。如果它在 BasicExample 中正常工作,那麼應用程式的 IMA 整合程式碼可能有問題。 請參閱本指南和 API 文件,偵測是否有差異。

問題仍然沒有解決嗎?歡迎前往 IMA SDK 論壇