Bắt đầu

SDK IMA giúp bạn dễ dàng tích hợp quảng cáo đa phương tiện vào trang web và ứng dụng của mình. SDK IMA có thể yêu cầu quảng cáo từ bất kỳ Máy chủ quảng cáo tuân thủ VAST và quản lý việc phát quảng cáo trong các ứng dụng của bạn. Với SDK phía máy khách IMA, bạn duy trì quyền kiểm soát việc phát lại nội dung video, còn SDK xử lý việc phát quảng cáo. Quảng cáo phát trong một trình phát video riêng biệt được đặt ở đầu trình phát video nội dung của ứng dụng.

Hướng dẫn này minh hoạ cách tích hợp SDK IMA vào một ứng dụng trình phát video đơn giản. Nếu bạn muốn muốn xem hoặc theo dõi một quá trình tích hợp mẫu hoàn chỉnh, hãy tải ví dụ đơn giản trên GitHub. Nếu bạn quan tâm đến trình phát HTML5 có tích hợp sẵn SDK, hãy xem Trình bổ trợ SDK IMA cho Video.js.

Tổng quan về phía máy khách IMA

Việc triển khai phía máy khách IMA bao gồm 4 thành phần SDK chính, như được minh hoạ trong hướng dẫn:

  • AdDisplayContainer: Đối tượng vùng chứa nơi quảng cáo được hiển thị.
  • AdsLoader: Đối tượng yêu cầu quảng cáo và xử lý các sự kiện từ phản hồi yêu cầu quảng cáo. Bạn chỉ nên tạo thực thể cho một trình tải quảng cáo có thể được sử dụng lại trong suốt thời gian hoạt động của ứng dụng.
  • AdsRequest: Đối tượng xác định yêu cầu quảng cáo. Yêu cầu quảng cáo chỉ định URL cho thẻ quảng cáo VAST, cũng như các thông số bổ sung, chẳng hạn như thứ nguyên quảng cáo.
  • AdsManager: Đối tượng chứa phản hồi cho yêu cầu quảng cáo, kiểm soát việc phát lại quảng cáo và lắng nghe quảng cáo các sự kiện do SDK kích hoạt.

Điều kiện tiên quyết

Trước khi bắt đầu, bạn cần có:

  • Ba tệp trống:
    • index.html
    • style.css
    • ads.js
  • Đã cài đặt Python trên máy tính hoặc máy chủ web để dùng cho việc kiểm thử

1. Khởi động máy chủ phát triển

Vì SDK IMA tải các phần phụ thuộc qua cùng một giao thức như trang mà SDK được tải từ đó, nên bạn cần sử dụng máy chủ web để kiểm tra ứng dụng của bạn. Cách đơn giản nhất để bắt đầu phát triển cục bộ sử dụng máy chủ được tích hợp sẵn của Python.

  1. Sử dụng một dòng lệnh, từ thư mục chứa tệpindex.html của bạn sẽ chạy:
      python -m http.server 8000
    
  2. Trên trình duyệt web, hãy truy cập vào http://localhost:8000/

Bạn cũng có thể sử dụng bất kỳ máy chủ web nào khác, chẳng hạn như Máy chủ HTTP Apache.

2. Tạo trình phát video đơn giản

Trước tiên, hãy sửa đổi index.html để tạo một phần tử video HTML5 đơn giản có trong gói và một nút để kích hoạt phát lại. Ngoài ra, hãy thêm các thẻ cần thiết để tải style.cssads.js. Sau đó, hãy sửa đổi styles.css để làm trình phát video thích ứng cho thiết bị di động. Cuối cùng, trong ads.js, hãy kích hoạt phát lại video khi nút được nhấp vào.

index.html
!<doctype html
>h<tml lang="en"<>/span>
  h<ead<>/span>
    t<itleI>MA HTML5 Simple Demo/<title
>    m<eta charset="utf-8"<>/span>
    m<eta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"<>/span>
    l<ink rel="stylesheet" href="style.css"<>/span>
  /<head
>  b<ody<>/span>
    d<iv id="page-content"<>/span>
      d<iv id="video-container"<>/span>
        v<ideo id="video-element"<>/span>
          s<ource src="https://storage.googleapis.com/interactive-media-ads/media/android.mp4"<>/span>
          s<ource src="https://storage.googleapis.com/interactive-media-ads/media/android.webm"<>/span>
        /<video
>      /<div
>      b<utton id="play-button"P>lay/<button
>    /<div
>    s<cript src="ads.js"/><script
>  /<body
>/<html
>
style.css
#page-content {
  position: relative;
  /* this element's width controls the effective height */
  /* of the video container's padding-bottom */
  max-width: 640px;
  margin: 10px auto;
}

#video-container {
  position: relative;
  /* forces the container to match a 16x9 aspect ratio */
  /* replace with 75% for a 4:3 aspect ratio, if needed */
  padding-bottom: 56.25%;
}

#video-element {
  /* forces the contents to fill the container */
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
ads.js
var videoElement;

// On window load, attach an event to the play button click
// that triggers playback on the video element
window.addEventListener('load', function(event) {
  videoElement = document.getElementById('video-element');
  var playButton = document.getElementById('play-button');
  playButton.addEventListener('click', function(event) {
    videoElement.play();
  });
});

Sau khi hoàn tất bước này, khi bạn mở index.html trong trình duyệt (thông qua phương thức phát triển của bạn máy chủ) bạn sẽ có thể xem phần tử video và video sẽ bắt đầu khi bạn nhấp vào nút phát.

3. Nhập SDK IMA

Tiếp theo, thêm khung IMA bằng cách sử dụng một thẻ tập lệnh trong index.html, trước thẻ cho ads.js.

index.html
...

        </video>
      </div>
      <button id="play-button">Play</button>
    </div>
    <script src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>
    <script src="ads.js"></script>
  </body>
</html>

4. Đính kèm trang và trình xử lý trình phát video

Để sửa đổi hành vi của trình phát video bằng JavaScript, hãy thêm các trình xử lý sự kiện kích hoạt các hành động sau:

  • Khi trang tải xong, hãy khởi chạy SDK IMA.
  • Khi người dùng nhấp vào nút phát video, hãy tải quảng cáo (trừ phi đã tải quảng cáo).
  • Khi cửa sổ trình duyệt được đổi kích thước, hãy cập nhật thành phần video và adsManager các phương diện giúp trang trở nên thích ứng với thiết bị di động
ads.js
var videoElement;
// Define a variable to track whether there are ads loaded and initially set it to false
var adsLoaded = false;

window.addEventListener('load', function(event) {
  videoElement = document.getElementById('video-element');
  initializeIMA();
  videoElement.addEventListener('play', function(event) {
    loadAds(event);
  });
  var playButton = document.getElementById('play-button');
  playButton.addEventListener('click', function(event) {
    videoElement.play();
  });
});

window.addEventListener('resize', function(event) {
  console.log("window resized");
});

function initializeIMA() {
  console.log("initializing IMA");
}

function loadAds(event) {
  // Prevent this function from running on if there are already ads loaded
  if(adsLoaded) {
    return;
  }
  adsLoaded = true;

  // Prevent triggering immediate playback when ads are loading
  event.preventDefault();

  console.log("loading ads");
}

5. Tạo vùng chứa quảng cáo

Trong hầu hết các trình duyệt, SDK IMA sử dụng một phần tử vùng chứa quảng cáo chuyên biệt để hiển thị cả quảng cáo và trên giao diện người dùng liên quan đến quảng cáo. Vùng chứa này phải có kích thước để phủ phần tử video từ góc trên cùng bên trái. Chiều cao và chiều rộng của quảng cáo đặt trong vùng chứa này được đặt bởi adsManager, vì vậy, bạn không cần đặt các giá trị này theo cách thủ công.

Để triển khai phần tử vùng chứa quảng cáo này, trước tiên hãy tạo một div mới trong Phần tử video-container. Sau đó, cập nhật CSS để định vị phần tử ở trên cùng bên trái góc video-element. Cuối cùng, hãy xác định biến cho vùng chứa trong Hàm initializeIMA() sẽ chạy khi trang được tải.

index.html
...

  <div id="video-container">
    <video id="video-element" controls>
      <source src="https://storage.googleapis.com/interactive-media-ads/media/android.mp4">
      <source src="https://storage.googleapis.com/interactive-media-ads/media/android.webm">
    </video>
    <div id="ad-container"></div>
  </div>

...
style.css
...

#ad-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}
ads.js
var videoElement;
var adsLoaded = false;
var adContainer;

...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
}

6. Khởi chạy AdsLoader và tạo yêu cầu quảng cáo

Để yêu cầu một tập hợp quảng cáo, hãy tạo một thực thể ima.AdsLoader. Phiên bản này lấy đối tượng AdDisplayContainer làm dữ liệu đầu vào và có thể dùng để xử lý Các đối tượng ima.AdsRequest liên kết với một URL thẻ quảng cáo đã chỉ định. Thẻ quảng cáo được sử dụng trong ví dụ này có chứa quảng cáo trước video 10 giây. Bạn có thể kiểm tra URL thẻ quảng cáo này hoặc bất kỳ URL nào bằng cách sử dụng Trình kiểm tra bộ video IMA.

Tốt nhất là bạn chỉ nên duy trì một thực thể của ima.AdsLoader cho toàn bộ vòng đời của một trang. Để thực hiện yêu cầu quảng cáo bổ sung, hãy tạo ima.AdsRequest mới nhưng sử dụng lại cùng một ima.AdsLoader. Để biết thêm thông tin, hãy xem Câu hỏi thường gặp về SDK IMA.

ads.js
var videoElement;
var adsLoaded = false;
var adContainer;
var adDisplayContainer;
var adsLoader;

...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
  adDisplayContainer = new google.ima.AdDisplayContainer(adContainer, videoElement);
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);

  // Let the AdsLoader know when the video has ended
  videoElement.addEventListener('ended', function() {
    adsLoader.contentComplete();
  });

  var adsRequest = new google.ima.AdsRequest();
  adsRequest.adTagUrl = 'https://pubads.g.doubleclick.net/gampad/ads?' +
      'iu=/21775744923/external/single_ad_samples&sz=640x480&' +
      'cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90&' +
      'gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=';

  // Specify the linear and nonlinear slot sizes. This helps the SDK to
  // select the correct creative if multiple are returned.
  adsRequest.linearAdSlotWidth = videoElement.clientWidth;
  adsRequest.linearAdSlotHeight = videoElement.clientHeight;
  adsRequest.nonLinearAdSlotWidth = videoElement.clientWidth;
  adsRequest.nonLinearAdSlotHeight = videoElement.clientHeight / 3;

  // Pass the request to the adsLoader to request ads
  adsLoader.requestAds(adsRequest);
}

7. Theo dõi các sự kiện AdsLoader

Khi quảng cáo được tải thành công, ima.AdsLoader sẽ phát ra một Sự kiện ADS_MANAGER_LOADED. Phân tích cú pháp sự kiện được truyền đến lệnh gọi lại để khởi chạy Đối tượng AdsManager. AdsManager tải các quảng cáo riêng lẻ như được xác định theo nội dung phản hồi quảng cáo URL của thẻ.

Ngoài ra, hãy nhớ xử lý mọi lỗi có thể xảy ra trong quá trình tải. Nếu quảng cáo không tải, hãy đảm bảo rằng quá trình phát nội dung nghe nhìn vẫn tiếp tục mà không có quảng cáo để không làm ảnh hưởng đến trải nghiệm của người dùng.

ads.js
var videoElement;
var adsLoaded = false;
var adContainer;
var adDisplayContainer;
var adsLoader;
var adsManager;

...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
  adDisplayContainer = new google.ima.AdDisplayContainer(adContainer, videoElement);
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);
  adsLoader.addEventListener(
      google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
      onAdsManagerLoaded,
      false);
  adsLoader.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR,
      onAdError,
      false);

...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  // Instantiate the AdsManager from the adsLoader response and pass it the video element
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);
}

function onAdError(adErrorEvent) {
  // Handle the error logging.
  console.log(adErrorEvent.getError());
  if(adsManager) {
    adsManager.destroy();
  }
}

8. Khởi động AdsManager

Để bắt đầu phát quảng cáo, bạn cần khởi động AdsManager. Để hỗ trợ đầy đủ cho thiết bị di động trình duyệt, điều này sẽ được kích hoạt bởi tương tác của người dùng.

ads.js
...

function loadAds(event) {
  // prevent this function from running on every play event
  if(adsLoaded) {
    return;
  }
  adsLoaded = true;

  // prevent triggering immediate playback when ads are loading
  event.preventDefault();

  console.log("loading ads");

  // Initialize the container. Must be done via a user action on mobile devices.
  videoElement.load();
  adDisplayContainer.initialize();

  var width = videoElement.clientWidth;
  var height = videoElement.clientHeight;
  try {
    adsManager.init(width, height, google.ima.ViewMode.NORMAL);
    adsManager.start();
  } catch (adError) {
    // Play the video without ads, if an error occurs
    console.log("AdsManager could not be started");
    videoElement.play();
  }
}

...

9. Phản hồi AdsManager

Để đảm bảo quảng cáo tự động thay đổi kích thước cho phù hợp với kích thước của trình phát video, nếu màn hình thay đổi kích thước hoặc hướng, thì sự kiện đổi kích thước cửa sổ phải gọi adsManager.resize().

ads.js
...

window.addEventListener('resize', function(event) {
  console.log("window resized");
  if(adsManager) {
    var width = videoElement.clientWidth;
    var height = videoElement.clientHeight;
    adsManager.resize(width, height, google.ima.ViewMode.NORMAL);
  }
});

...

10. Theo dõi các sự kiện AdsManager

AdsManager cũng kích hoạt một số sự kiện cần phải được xử lý. Những sự kiện này sẽ được sử dụng để theo dõi các thay đổi về trạng thái, kích hoạt phát và tạm dừng video nội dung và đăng ký các lỗi.

Xử lý lỗi

Trình xử lý lỗi được tạo cho AdsLoader có thể đóng vai trò là trình xử lý lỗi cho AdsManager bằng cách thêm một trình xử lý sự kiện mới có cùng hàm callback.

ads.js
...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);

  adsManager.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR,
      onAdError);
}

...

Kích hoạt sự kiện phát và tạm dừng

Khi sẵn sàng chèn quảng cáo để hiển thị, AdsManager sẽ kích hoạt Sự kiện CONTENT_PAUSE_REQUESTED. Hãy xử lý sự kiện này bằng cách kích hoạt một nút tạm dừng trên trình phát video cơ bản. Tương tự, khi một quảng cáo hoàn tất, AdsManager sẽ kích hoạt Sự kiện CONTENT_RESUME_REQUESTED. Hãy xử lý sự kiện này bằng cách bắt đầu phát lại trên video nội dung cơ bản.

ads.js
...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);

  adsManager.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR,
      onAdError);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
      onContentPauseRequested);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
      onContentResumeRequested);
}

...

function onContentPauseRequested() {
  videoElement.pause();
}

function onContentResumeRequested() {
  videoElement.play();
}

Kích hoạt lượt nhấp để tạm dừng trên thiết bị di động

AdContainer phủ lên thành phần video nên người dùng không thể tương tác trực tiếp trình phát cơ bản. Điều này có thể khiến người dùng trên thiết bị di động nhầm lẫn, những người mong muốn có thể nhấn trình phát video để tạm dừng phát. Để giải quyết vấn đề này, SDK IMA chuyển mọi lượt nhấp không được được IMA xử lý từ lớp phủ quảng cáo đến phần tử AdContainer để có thể đã xử lý. Điều này không áp dụng cho quảng cáo tuyến tính trên các trình duyệt không dành cho thiết bị di động, vì việc nhấp vào quảng cáo sẽ mở ra nhấp vào liên kết.

Để triển khai tính năng nhấp để tạm dừng, hãy thêm một trình xử lý lượt nhấp vào AdContainer và kích hoạt phát hoặc tạm dừng các sự kiện trên video ban đầu.

ads.js
...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
  adContainer.addEventListener('click', adContainerClick);
  adDisplayContainer = new google.ima.AdDisplayContainer(adContainer, videoElement);
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);

...

function adContainerClick(event) {
  console.log("ad container clicked");
  if(videoElement.paused) {
    videoElement.play();
  } else {
    videoElement.pause();
  }
}

...

Kích hoạt phát trên quảng cáo phi tuyến tính

AdsManager sẽ tạm dừng video nội dung khi quảng cáo đã sẵn sàng phát, nhưng điều này không tính đến quảng cáo phi tuyến tính, nơi nội dung sẽ tiếp tục phát trong khi quảng cáo được hiển thị. Để hỗ trợ quảng cáo phi tuyến tính, hãy theo dõi AdsManager để phát ra Sự kiện LOADED. Sau đó, kiểm tra xem quảng cáo có tuyến tính hay không và nếu không, hãy tiếp tục phát trên phần tử video.

ads.js
...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);

  adsManager.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR,
      onAdError);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
      onContentPauseRequested);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
      onContentResumeRequested);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.LOADED,
      onAdLoaded);
}

...

function onAdLoaded(adEvent) {
  var ad = adEvent.getAd();
  if (!ad.isLinear()) {
    videoElement.play();
  }
}

Vậy là xong! Giờ đây, bạn đang yêu cầu và hiển thị quảng cáo bằng SDK IMA. Để tìm hiểu thêm các tính năng SDK nâng cao, hãy xem các hướng dẫn khác hoặc mẫu trên GitHub.