IMA SDK 可用於在直播和隨選影片營利。 如果是直播影片,您需要為每個廣告插播建立新的廣告請求。 請分散這些要求,確保所有觀眾不會同時請求廣告,且廣告伺服器過於龐大。
為協助完成這項作業,IMA SDK 含有 AdsRequest.liveStreamPrefetchSeconds
屬性。這項屬性會指定您呼叫 AdsLoader.requestAds()
後, SDK 應等待的秒數上限,系統將隨機挑選實際要求時間。舉例來說,如果您將 AdsRequest.liveStreamPrefetchSeconds
設為 30,則在您呼叫 AdsLoader.requestAds()
後,SDK 會等待 0 到 30 秒,以便實際向伺服器提出要求。
直播預先擷取功能
建議您在廣告插播結束後立即預先擷取下一個廣告插播時間點。 這樣可確保您的預先擷取時間長度上限。 假設您的廣告插播之間有 5 分鐘。廣告插播結束時,您可以使用 290 秒的預先擷取視窗 (5 分鐘減 10 秒),確保預先擷取視窗結束時傳送的請求有足夠的時間可以解決下一個廣告插播:
// 5 minutes == 300 seconds. Include a 10 second buffer
var AD_INTERVAL = 290;
function onAdEvent(adEvent) {
var ad = adEvent.getAd();
switch(adEvent.type) {
case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
// Pre-fetch our next ad break.
requestAds();
// Play those ads in 5 minutes. In a real-world implementation,
// this is likely done as the result of a message from your
// streaming server, not a timeout.
setTimeout(playAds, AD_INTERVAL * 1000);// Convert to ms.
}
}
function requestAds() {
// Destroy the current AdsManager, in case the tag you requested previously
// contains post-rolls (don't play those now).
if (adsManager) {
adsManager.destroy();
}
// Your AdsLoader will be set up on page-load. You should re-use the same
// AdsLoader for every request. For more info on setting up the AdsLoader,
// see the "Get Started" guide in the prerequisites above.
if (adsLoader) {
// Reset the IMA SDK.
adsLoader.contentComplete();
}
var adsRequest = new google.ima.AdsRequest();
adsRequest.adTagUrl = '...';
adsRequest.linearAdSlotWidth = <linear_width>;
adsRequest.linearAdSlotHeight = <linear_height>;
adsRequest.nonLinearAdSlotWidth = <nonlinear_width>;
adsRequest.nonLinearAdSlotHeight = <nonlinear_height>;
adsRequest.liveStreamPrefechSeconds = AD_INTERVAL;
adsLoader.requestAds(adsRequest);
}
function playAds() {
adsManager.init(
<linear_width>, <linear_height>, google.ima.ViewMode.NORMAL);
adsManager.start();
}