开始使用 IMA DAI SDK

IMA SDK 可让您轻松地将多媒体广告集成到您的网站和应用中。IMA SDK 可以 向任意 <ph type="x-smartling-placeholder"></ph> 符合 VAST 标准的广告服务器,并管理应用中的广告播放。借助 IMA DAI SDK,应用 针对广告和内容视频(VOD 或直播内容)的视频流请求。然后,SDK 会返回 组合视频流,因此您无需管理在广告与内容视频之间的切换 。

选择您感兴趣的 DAI 解决方案

<ph type="x-smartling-placeholder"></ph>

全方位服务 DAI

本指南将演示如何将 IMA DAI SDK 集成到简单的视频播放器中 应用。如果您想查看或了解已完成的示例 集成,请从以下位置下载 BasicExample GitHub。

IMA DAI 概览

实施 IMA DAI 涉及四个主要 SDK 组件,如本视频所示 指南:

  • StreamDisplayContainer: 一种容器对象,位于视频播放元素上层,用于存放广告界面元素。
  • AdsLoader: 用于请求数据流并处理由数据流请求响应对象触发的事件的对象。 只应实例化一个广告加载器,并且该加载器可在 应用。
  • StreamRequest: 用于定义数据流请求的对象。视频流请求可以是点播视频或直播请求 。请求会指定内容 ID 以及 API 密钥或身份验证令牌和其他 参数。
  • StreamManager: 用于处理动态广告插播数据流以及与 DAI 后端的互动的对象。通过 视频流管理器还处理跟踪 ping,并将视频流和广告事件转发到 发布商。

前提条件

下载并运行示例视频播放器应用

示例应用提供了一个可正常运行的视频播放器,用于播放 HLS 视频。用作 集成 IMA DAI SDK 的 DAI 功能的起点。

  1. 下载示例视频播放器 app 和 提取。

  2. 启动 Android Studio,然后选择 Open an existing Android Studio project, 或者,如果 Android Studio 已在运行,请选择 File >新建 >导入 项目。然后选择 SampleVideoPlayer/build.gradle

  3. 依次选择 Tools >Android >Sync Project with Gradle Files

  4. 确保播放器应用可在实体 Android 设备上编译和运行,或 Android 虚拟设备(使用 Run >Run 'app'。这对于该视频来说很正常 需要一点时间才能加载完毕,然后再播放。

查看示例视频播放器

示例视频播放器尚无任何 IMA DAI SDK 集成代码。 示例应用包含两个主要部分:

  1. samplevideoplayer/SampleVideoPlayer.java:An 基于 ExoPlayer 的 HLS 播放器,用作 IMA DAI 集成的基础。

  2. videoplayerapp/MyActivity.java:此 activity 会创建视频播放器, 并向其传递 ContextSimpleExoPlayerView

将 IMA DAI SDK 添加到播放器应用

您还必须添加对 IMA DAI SDK 的引用。在 Android Studio 中,添加 您的应用级 build.gradle 文件(位于 app/build.gradle

repositories {
  google()
  mavenCentral()
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'androidx.media3:media3-exoplayer:1.3.1'
    implementation 'com.google.ads.interactivemedia.v3:interactivemedia:3.35.0'
}

集成 IMA DAI SDK

  1. videoplayerapp 软件包中创建一个名为 SampleAdsWrapper 的新类 (在 app/java/com.google.ads.interactivemedia.v3.samples/videoplayerapp/ 中)更改为 封装现有的 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 {
    
        // Livestream 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 = "2548831";
        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. AdsLoader 添加 buildStreamRequest() 方法,以便它可以请求 与广告一起直播这是包含广告的直播(默认设置)或 点播式(VOD) 视频流,播放预先录制的内容和广告。接收者 启用 VOD 视频流,注释掉直播请求,并取消注释 VOD 视频流请求。

    要想使用 DAI,播放器必须将直播活动的 ID3 事件传递给 IMA DAI SDK。在下面的示例代码中,这是由 callback.onUserTextReceived() 方法结合使用。

    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);
                        }
                    }
                });
    
        // Livestream 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 livestream 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());
            }
    
            @Override
            public int getVolume() {
                return videoPlayer.getVolume();
            }
        };
        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 的布局文件 activity_my.xml,以便为 日志记录。

    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 集成代码。

如果仍有问题,请访问 IMA SDK 论坛