ExoPlayer là trình phát nội dung đa phương tiện ở cấp ứng dụng dành cho Android. Hướng dẫn này cho thấy cách bạn có thể sử dụng tiện ích IMA ExoPlayer bao bọc SDK IMA DAI để yêu cầu và phát luồng nội dung nghe nhìn với cả quảng cáo và nội dung.
Dưới đây là một số lợi ích của tiện ích:
- Đơn giản hóa mã cần thiết để tích hợp IMA với các tính năng.
- Giảm thời gian phát triển cần thiết để cập nhật lên phiên bản IMA mới.
Tiện ích IMA của ExoPlayer hỗ trợ các giao thức truyền trực tuyến HLS và DASH. Dưới đây là bản tóm tắt:
Hỗ trợ luồng tiện ích ExoPlayer-IMA | ||
---|---|---|
Sự kiện phát trực tiếp | Sự kiện phát trực tiếp VOD (video theo yêu cầu) | |
HLS (Phát trực tuyến dựa trên HTTP) | ||
DASH (Truyền phát thích ứng động qua HTTP) |
Phát trực tiếp DASH được hỗ trợ trên ExoPlayer-IMA phiên bản 1.1.0 trở lên.
Hướng dẫn này dựa trên hướng dẫn của ExoPlayer và trình bày cách tạo một ứng dụng hoàn chỉnh và tích hợp tiện ích. Hãy xem ExoPlayerExample
trên GitHub để biết ví dụ với một ứng dụng mẫu hoàn chỉnh.
Điều kiện tiên quyết
- Android Studio
- AndroidX Media3 ExoPlayer phiên bản 1.0.0 trở lên để hỗ trợ DAI.
Tạo một dự án Android Studio mới
Để tạo dự án Android Studio, hãy hoàn tất các bước sau:
- Khởi động Android Studio.
- Chọn Bắt đầu dự án Android Studio mới.
- Trên trang Chọn dự án của bạn, hãy chọn mẫu Không có hoạt động nào.
- Nhấp vào Tiếp theo.
Trên trang Configure your project (Định cấu hình dự án), hãy đặt tên cho dự án rồi chọn Java cho ngôn ngữ.
Nhấp vào Hoàn tất.
Thêm tiện ích IMA ExoPlayer vào dự án của bạn
Thêm các lệnh nhập cho tiện ích này vào tệp build.gradle ở cấp ứng dụng trong mục dependencies
.
Định cấu hình ứng dụng và bật multidex. Điều này là cần thiết do kích thước của tiện ích và là bắt buộc đối với các ứng dụng có minSdkVersion
được đặt thành Android 4.4W (API cấp 20) trở xuống.
Ví dụ:
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.1.1' implementation 'androidx.media3:media3-exoplayer:1.1.1' implementation 'androidx.media3:media3-exoplayer-hls:1.1.1' implementation 'androidx.media3:media3-exoplayer-dash:1.1.1' // Adding the ExoPlayer IMA extension for ads will also include the IMA // SDK as a dependency. implementation 'androidx.media3:media3-exoplayer-ima:1.1.1' }
Thêm quyền người dùng mà SDK IMA DAI yêu cầu để yêu cầu quảng cáo:
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>
Thêm nội dung khai báo ý định
Nếu ứng dụng của bạn nhắm đến Android 11 (API cấp 30) trở lên, thì các phiên bản hiện tại và gần đây của SDK IMA DAI sẽ yêu cầu bạn phải khai báo rõ ràng ý định để mở đường liên kết trang web. Thêm đoạn mã sau vào tệp kê khai của ứng dụng để cho phép nhấp vào quảng cáo (người dùng nhấp vào nút Tìm hiểu thêm).
<?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>
Thiết lập giao diện người dùng của ExoPlayer
Tạo đối tượng PlayerView
cho ExoPlayer sử dụng.
Thay đổi androidx.constraintlayout.widget.ConstraintLayout
thành LinearLayout
(nên dùng cho tiện ích IMA của ExoPlayer).
Ví dụ:
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>
Thêm thông số luồng của bạn
Hãy xem trang phát trực tuyến mẫu IMA để biết các tài sản luồng mẫu dùng để kiểm thử dự án của bạn. Ngoài ra, hãy xem phần Ad Manager trên DAI để biết thông tin về cách thiết lập luồng của riêng bạn.
Bước này minh hoạ cách thiết lập sự kiện phát trực tiếp, nhưng tiện ích IMA của ExoPlayer cũng hỗ trợ các luồng VOD DAI. Xem bước phát trực tiếp video theo yêu cầu (VOD) để biết ứng dụng của bạn cần thay đổi những gì để xử lý các luồng VOD.
Nhập tiện ích IMA ExoPlayer
Thêm câu lệnh nhập cho tiện ích ExoPlayer.
Thêm các biến riêng tư sau đây vào MyActivity.java
:
PlayerView
ExoPlayer
ImaServerSideAdInsertionMediaSource.AdsLoader
ImaServerSideAdInsertionMediaSource.AdsLoader.State
Thêm khoá tài sản của luồng HLS (Phát trực tiếp) Big Buck Bunny (Live) (Phát trực tiếp) để kiểm thử với sự kiện phát trực tiếp này. Bạn có thể thử nghiệm nhiều luồng khác trên trang luồng mẫu của IMA.
Tạo hằng số KEY_ADS_LOADER_STATE
để lưu và truy xuất trạng thái AdsLoader
.
Ví dụ:
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; ... 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 ImaServerSideAdInsertionMediaSource.AdsLoader adsLoader; private ImaServerSideAdInsertionMediaSource.AdsLoader.State adsLoaderState; }
Tạo một thực thể adsLoader
Ghi đè phương thức onCreate
để tìm PlayerView
và kiểm tra một AdsLoader.State
đã lưu (có thể dùng khi khởi tạo đối tượng adsLoader
).
Ngoài ra, hãy bật multidex nếu được số lượng phương thức của ứng dụng yêu cầu và minSdkVersion
(như giải thích trong bước 2).
Ví dụ:
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 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); 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); } } } }
Thêm phương thức để khởi chạy trình phát
Thêm một phương thức để khởi chạy trình phát và làm như sau:
- Tạo một thực thể
AdsLoader
. - Tạo
ExoPlayer
. - Tạo
MediaItem
bằng khoá tài sản của sự kiện phát trực tiếp. - Đặt
MediaItem
cho trình phát của bạn.
Ví dụ:
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.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); } }
Thêm phương thức để huỷ bỏ trình phát
Thêm phương thức để giải phóng trình phát theo trình tự sau:
- Đặt tham chiếu của trình phát thành rỗng và giải phóng tài nguyên của người chơi.
- Giải phóng trạng thái của
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(); }
Xử lý sự kiện của người chơi
Cuối cùng, hãy tạo lệnh gọi lại cho các sự kiện trong vòng đời của hoạt động để xử lý quá trình phát trong luồng.
Cách hỗ trợ SDK Android phiên bản 24 trở lên:
Để hỗ trợ phiên bản SDK Android thấp hơn 24:
– onResume()
– onPause()
onStart()
và onResume()
ánh xạ đến playerView.onResume()
, còn onStop()
và onPause()
ánh xạ đến playerView.onPause()
.
Bước này cũng sử dụng sự kiện
onSaveInstanceState()
để cố gắng lưu 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()); } } ... }
Thiết lập luồng VOD (không bắt buộc)
Nếu ứng dụng của bạn cần phải phát nội dung VOD có quảng cáo, thì bạn cần phải làm như sau:
- Thêm
CMS ID
vàVideo ID
cho sự kiện phát trực tiếp thử nghiệm VOD. - Tạo URI SSAI VOD bằng
ImaServerSideAdInsertionUriBuilder()
. - Hãy dùng URI mới này làm mục nội dung đa phương tiện trên trình phát của bạn.
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); }
Vậy là xong! Giờ đây, bạn đang yêu cầu và phát luồng nội dung đa phương tiện bằng tiện ích ExoPlayer IMA. Hãy xem mẫu Android DAI trên GitHub để biết mã hoàn chỉnh.