在影片內容中顯示廣告Show ads in video content

警告

從2020年6月1日起,適用于 Windows UWP 應用程式的 Microsoft Ad 營收平臺將會關閉。As of June 1, 2020, the Microsoft Ad Monetization platform for Windows UWP apps will be shut down. 深入了解Learn more

本文會逐步說明如何使用 AdScheduler 類別在使用 JavaScript 和 HTML 撰寫的通用 Windows 平台 (UWP) App 的影片內容中顯示廣告。This walkthrough shows how to use the AdScheduler class to show ads in video content in a Universal Windows Platform (UWP) app that was written using JavaScript with HTML.

注意

目前只有使用 JavaScript 與 HTML 撰寫的 UWP app 支援此功能。This feature is currently supported only for UWP apps that are written using JavaScript with HTML.

AdScheduler 可搭配漸進式和串流處理媒體,並使用 IAB 標準 Video Ad Serving Template (VAST) 2.0/3.0 和 VMAP 承載格式。AdScheduler works with both progressive and streaming media, and uses IAB standard Video Ad Serving Template (VAST) 2.0/3.0 and VMAP payload formats. 如果使用標準,AdScheduler 就無從得知所互動的廣告服務。By using standards, AdScheduler is agnostic to the ad service with which it interacts.

影片內容的廣告根據程式少於 10 分鐘 (短時間形式) 或超過 10 分鐘 (長時間形式) 而有所不同。Advertising for video content differs based upon whether the program is under ten minutes (short form), or over ten minutes (long form). 雖然要在服務上設定後者比較複雜,但是寫入用戶端程式碼的方式實際上沒有任何差異。Although the latter is more complicated to set up on the service, there is actually no difference in how one writes the client side code. 如果 AdScheduler 收到含單一廣告而不是資訊清單的 VAST 承載,就會被視為如同為單一預載廣告 (在時間 00:00 的一個中斷) 呼叫的資訊清單。If the AdScheduler receives a VAST payload with a single ad instead of a manifest, it is treated as if the manifest called for a single pre-roll ad (one break at time 00:00).

先決條件Prerequisites

  • 使用 Visual Studio 2015 或更新版本安裝 Microsoft Advertising SDKInstall the Microsoft Advertising SDK with Visual Studio 2015 or a later release.

  • 您的專案必須使用 MediaPlayer 控制項來播放將排定廣告的影片內容。Your project must use the MediaPlayer control to serve the video content in which the ads will be scheduled. 此控制項可從 GitHub 上 Microsoft 提供的 TVHelpers 程式庫集合中取得。This control is available in the TVHelpers collection of libraries available from Microsoft on GitHub.

    下列範例顯示如何在 HTML 標記中宣告 MediaPlayerThe following example shows how to declare a MediaPlayer in HTML markup. 這個標記通常屬於 index.html 檔案 (或其他 html 檔案,視您的專案而定) 中的 <body> 區段。Typically, this markup belongs in the <body> section in the index.html file (or another html file as appropriate for your project).

    <div id="MediaPlayerDiv" data-win-control="TVJS.MediaPlayer">
      <video src="URL to your content">
      </video>
    </div>
    

    下列範例顯示如何在 JavaScript 程式碼中建立 MediaPlayerThe following example shows how to establish a MediaPlayer in JavaScript code.

    var mediaPlayerDiv = document.createElement("div");
    document.body.appendChild(mediaPlayerDiv);
    
    var videoElement = document.createElement("video");
    videoElement.src = "<URL to your content>";
    mediaPlayerDiv.appendChild(videoElement);
    
    var mediaPlayer = new TVJS.MediaPlayer(mediaPlayerDiv);
    

如何在您的程式碼中使用 AdScheduler 類別How to use the AdScheduler class in your code

  1. 在 Visual Studio 中,開啟您的專案或建立新專案。In Visual Studio, open your project or create a new project.

  2. 如果專案的目標是 [任何 CPU],請將您的專案更新成使用架構特定的建置輸出 (例如,[x86])。If your project targets Any CPU, update your project to use an architecture-specific build output (for example, x86). 如果專案的目標是 [任何 CPU],您將無法於下列步驟中成功加入 Microsoft 廣告庫的參考。If your project targets Any CPU, you will not be able to successfully add a reference to the Microsoft advertising library in the following steps. 如需詳細資訊,請參閱專案中因目標為 [任何 CPU] 所造成的參考錯誤For more information, see Reference errors caused by targeting Any CPU in your project.

  3. Microsoft Advertising SDK for JavaScript 程式庫的參考新增至您的專案。Add a reference to the Microsoft Advertising SDK for JavaScript library to your project.

    1. 在 [方案總管]**** 視窗中的 [參考]**** 上按一下滑鼠右鍵,然後選取 [加入參考]****。From the Solution Explorer window, right click References, and select Add Reference…
    2. 在 [參考管理員]**** 中,展開 [通用 Windows]****、按一下 [擴充功能]****,然後選取 [Microsoft Advertising SDK for JavaScript]**** (Version 10.0) 旁邊的核取方塊。In Reference Manager, expand Universal Windows, click Extensions, and then select the check box next to Microsoft Advertising SDK for JavaScript (Version 10.0).
    3. 在 [參考管理員]**** 中,按一下 [確定]。In Reference Manager, click OK.
  4. 將 AdScheduler.js 檔案新增到您的專案︰Add the AdScheduler.js file to your project:

    1. 在 Visual Studio 中,按一下 [專案]**** 和 [管理 NuGet 套件]****。In Visual Studio, click Project and Manage NuGet Packages.
    2. 在搜尋方塊中,輸入 Microsoft.StoreServices.VideoAdScheduler 並安裝 Microsoft.StoreServices.VideoAdScheduler 套件。In the search box, type Microsoft.StoreServices.VideoAdScheduler and install the Microsoft.StoreServices.VideoAdScheduler package. AdScheduler.js 檔案會新增到您專案中的 ../js 子目錄。The AdScheduler.js file is added to the ../js subdirectory in your project.
  5. 開啟 index.html 檔案 (或其他適用於您專案的 HTML 檔案)。Open the index.html file (or other html file as appropriate for your project). <head> 區段中,在專案的 default.css 和 main.js JavaScript 參考後面新增 ad.js 和 adscheduler.js 的參考。In the <head> section, after the project’s JavaScript references of default.css and main.js, add the reference to ad.js and adscheduler.js.

    <script src="//Microsoft.Advertising.JavaScript/ad.js"></script>
    <script src="/js/adscheduler.js"></script>
    

    注意

    這一行必須放在 <head> 區段所包含的 main.js 之後,否則建置專案時會發生錯誤。This line must be placed in the <head> section after the include of main.js; otherwise, you will encounter an error when you build your project.

  6. 在專案的 main.js 檔案中,新增建立新 AdScheduler 物件的程式碼。In the main.js file in your project, add code that creates a new AdScheduler object. 傳入裝載影片內容的 MediaPlayerPass in the MediaPlayer that hosts your video content. 程式碼必須放在 WinJS.UI.processAll 後面執行。The code must be placed so that it runs after WinJS.UI.processAll.

    var myMediaPlayer = document.getElementById("MediaPlayerDiv");
    var myAdScheduler = new MicrosoftNSJS.Advertising.AdScheduler(myMediaPlayer);
    
  7. 使用 AdScheduler 物件的 requestSchedulerequestScheduleByUrl 方法向伺服器要求廣告排程,並將它插入 MediaPlayer 時間軸,然後播放影片媒體。Use the requestSchedule or requestScheduleByUrl methods of the AdScheduler object to request an ad schedule from the server and insert it into the MediaPlayer timeline, and then play the video media.

    • 如果您是獲得向 Microsoft 廣告伺服器要求廣告排程權限的 Microsoft 合作夥伴,請使用 requestSchedule 並指定由您的 Microsoft 代表提供給您的應用程式識別碼和單位識別碼。If you are a Microsoft partner who has received permission to request an ad schedule from the Microsoft ad server, use requestSchedule and specify the application ID and ad unit ID that were provided to you by your Microsoft representative.

      這個方法採用承諾 形式,它是一種非同步建構,其中傳遞了兩個功能指標:一個指標在承諾成功完成時呼叫onComplete 函數,另一個指標在遇到錯誤時呼叫 onError 函數。This method takes the form of a Promise, which is an asynchronous construct where two function pointers are passed: a pointer for the onComplete function to call when the promise completes successfully and a pointer for the onError function to call if an error is encountered. onComplete 函數中,開始播放視訊內容。In the onComplete function, start playback of your video content. 廣告將在已排程的時間開始播放。The ad will start playing at the scheduled time. 在您 onError 函數中,處理錯誤,然後開始播放視訊。In your onError function, handle the error and then start playback of your video. 您的視訊內容在播放時不會有廣告。Your video content will play without an ad. onError 函數的引數包含下列成員的物件。The argument of the onError function is an object that contains the following members.

      myAdScheduler.requestSchedule("your application ID", "your ad unit ID").then(
        function promiseSuccessHandler(schedule) {
            // Success: play the video content with the scheduled ads.
            myMediaPlayer.tvControl.play();
        },
        function promiseErrorHandler(err) {
            // Error: play the video content without the ads.
            myMediaPlayer.tvControl.play();
        });
      
    • 若要向非 Microsoft 廣告伺服器要求廣告排程,請使用 requestScheduleByUrl,然後傳入伺服器 URI。To request an ad schedule from a non-Microsoft ad server, use requestScheduleByUrl, and pass in the server URI. 這種方法也採用 Promise 的形式,它接受 onCompleteonError 函數的指標。This method also takes the form of a Promise that accepts pointers for the onComplete and onError functions. 從伺服器傳回的廣告承載必須符合視訊廣告服務樣板 (VAST) 或視訊多廣告播放列表 (VMAP) 承載格式。The ad payload that is returned from the server must conform to the Video Ad Serving Template (VAST) or Video Multiple Ad Playlist (VMAP) payload formats.

      myAdScheduler.requestScheduleByUrl("your URL").then(
        function promiseSuccessHandler(schedule) {
            // Success: play the video content with the scheduled ads.
            myMediaPlayer.winControl.play();
        },
        function promiseErrorHandler(evt) {
            // Error: play the video content without the ads.
            myMediaPlayer.winControl.play();
        });
      

    注意

    在開始播放 MediaPlayer 中的主要返回。內容之前,您應該等待 requestSchedulerequestScheduleByUrl 傳回。You should wait for requestSchedule or requestScheduleByUrl to return before starting to play the primary video content in the MediaPlayer. requestSchedule 傳回之前開始播放媒體 (在預載廣告的情况下) 將導致預載中斷主視訊內容。Starting to play media before requestSchedule returns (in the case of a pre-roll advertisement) will result in the pre-roll interrupting the primary video content. 即使函數失敗,您還是必須呼叫 play,因為 AdScheduler 會告訴 MediaPlayer 略過廣告並直接移動到內容。You must call play even if the function fails, because the AdScheduler will tell the MediaPlayer to skip the ad(s) and move straight to the content. 您可能有不同的商務需求,例如若無法從遠端成功擷取廣告,則插入內建的廣告。You may have a different business requirement, such as inserting a built-in ad if an ad can't be successfully fetched remotely.

  8. 在播放時,您可以處理其他事件,這些事件可讓您的應用程式追蹤進度和/或初始廣告符合處理程序之後可能發生的錯誤。During playback, you can handle additional events that let your app track progress and/or errors which may occur after the initial ad matching process. 下列程式碼顯示其中一部分事件,包含 onPodStartonPodEndonPodCountdownonAdProgressonAllCompleteonErrorOccurredThe following code shows some of these events, including onPodStart, onPodEnd, onPodCountdown, onAdProgress, onAllComplete, and onErrorOccurred.

    // Raised when an ad pod starts. Make the countdown timer visible.
    myAdScheduler.onPodStart = function (sender, data) {
        myCounterDiv.style.visibility = "visible";
    }
    
    // Raised when an ad pod ends. Hide the countdown timer.
    myAdScheduler.onPodEnd = function (sender, data) {
        myCounterDiv.style.visibility = "hidden";
    }
    
    // Raised when an ad is playing and indicates how many seconds remain  
    // in the current pod of ads. This is useful when the app wants to show 
    // a visual countdown until the video content resumes.
    myAdScheduler.onPodCountdown = function (sender, data) {
        myCounterText = "Content resumes in: " +
        Math.ceil(data.remainingPodTime) + " seconds.";
    }
    
    // Raised during each quartile of progress through the ad clip.
    myAdScheduler.onAdProgress = function (sender, data) {
    }
    
    // Raised when the ads and content are complete.
    myAdScheduler.onAllComplete = function (sender) {
    }
    
    // Raised when an error occurs during playback after successfully scheduling.
    myAdScheduler.onErrorOccurred = function (sender, data) {
    }
    

AdScheduler 成員AdScheduler members

本節提供有關 AdScheduler 物件成員的一些詳細資訊。This section provides some details about the members of the AdScheduler object. 如需有關這些成員的詳細資訊,請參閱專案中 AdScheduler.js 檔案中的註解和定義。For more information about these members, see the comments and definitions in the AdScheduler.js file in your project.

requestSchedulerequestSchedule

這個方法會從 Microsoft 廣告伺服器要求廣告排程,並將其插入到傳遞給 AdScheduler 建構函式的 MediaPlayer 的時間軸中。This method requests an ad schedule from the Microsoft ad server and inserts it into the timeline of the MediaPlayer that was passed to the AdScheduler constructor.

選用的第三個參數 (adTags) 是名稱/值組的 JSON 集合,可用於有進階目標的應用程式。The optional third paramter (adTags) is a JSON collection of name/value pairs that can be used for apps that have advanced targeting. 例如,播放各種自動連結到的影片的應用程式可能會以顯示中車輛的製造和型號來補充廣告單元 ID。For example, an app that plays a variety of auto-related videos might supplement the ad unit ID with the make and model of the car being shown. 此參數僅供有收到 Microsoft 核准使用廣告標記的合作夥伴使用。This parameter is intended to be used only by partners who receive approval from Microsoft to use ad tags.

參照 adTags 時應注意下列事項:The following items should be noted when referring to adTags:

  • 此參數是一個很少使用的選項。This parameter is a very rarely used option. 在使用 adTags 之前,發行者必須與 Microsoft 密切合作。The publisher must work closely with Microsoft before using adTags.
  • 名稱和值必須在廣告服務上預先定義。Both the names and the values must be predetermined on the ad service. 廣告標記不是開放式搜尋字詞或關鍵字。Ad tags are not open ended search terms or keywords.
  • 支援的標籤數上限是 10。The maximum supported number of tags is 10.
  • 標記名稱限制為 16 個字元。Tag names are restricted to 16 characters.
  • 標記值上限是 128 個字元。Tag values have a maximum of 128 characters.

requestScheduleByUrirequestScheduleByUri

這個方法會從 URI 中指定的非 Microsoft 廣告伺服器要求廣告排程,並將其插入到傳遞給 AdScheduler 建構函式的 MediaPlayer 的時間軸中。This method requests an ad schedule from the non-Microsoft ad server specified in the URI and inserts it into the timeline of the MediaPlayer that was passed to the AdScheduler constructor. 廣告伺服器傳回的廣告承載必須符合視訊廣告服務樣板 (VAST) 或視訊多廣告播放列表 (VMAP) 承載格式。The ad payload that is returned by the ad server must conform to the Video Ad Serving Template (VAST) or Video Multiple Ad Playlist (VMAP) payload formats.

mediaTimeoutmediaTimeout

此内容取得或設定媒體必須可播放的毫秒數。This property gets or sets the number of milliseconds that the media must be playable. 設定為 0 的值通知系統永遠不要啟動逾時功能。A value of 0 informs the system to never timeout. 預設值是 30000 毫秒 (30 秒)。The default is 30000 ms (30 seconds).

playSkippedMediaplaySkippedMedia

此内容的取得或設定一個 布林 值,該值可判別當使用者略過已排程的開始時間時,是否會播放已排程的媒體。This property gets or sets a Boolean value that indicates whether scheduled media will play if user skips ahead to a point past a scheduled start time.

廣告用戶端和媒體播放機將根據主要視訊內容的向前快轉和倒帶期間所發生的廣告情況來執行條款中規則。The ad client and media player will enforce rules in terms what happens to advertisements during fast forwarding and rewinding of the primary video content. 在大多數情況下,應用程式開發人員不允許完全略過廣告,但希望為使用者提供合理的體驗。In most cases, app developers do not allow advertisements to be entirely skipped over but do want to provide a reasonable experience for the user. 下列兩個選項符合大部分開發人員的需求:The following two options fall within the needs of most developers:

  1. 允許終端使用者隨意略過廣告 Pod。Allow end-users to skip over advertisement pods at will.
  2. 允許使用者略過廣告 Pod,但在播放恢復時會播放最新的 Pod。Allow users to skip over advertisement pods but play the most recent pod when playback resumes.

PlaySkippedMedia 屬性有下列條件:The playSkippedMedia property has the following conditions:

  • 廣告開始後,無法略過或向前快轉廣告。Advertisements cannot be skipped or fast forwarded once the advertisement begins.
  • 廣告 Pod 中的所有廣告都會在 Pod 開始後播放。All advertisements in an advertisement pod will play once the pod has started.
  • 一旦播放,廣告將不會在主要內容 (電影、影集等) 中播放,廣告標記會標示為播放或刪除。Once played, an advertisement will not play again during the primary content (movie, episode, etc.); advertisement markers will be marked as played or removed.
  • 預先推出的廣告無法略過。Pre-rollout advertisements cannot be skipped.

當恢復包含廣告的內容時,請將 playSkippedMedia 設定為 false 以略過預先預告片,並防止最近的廣告播放。When resuming content that contains advertising, set playSkippedMedia to false to skip pre-rolls and prevent the most recent ad break from playing. 然後,內容開始後,將 playSkippedMedia 設定為 true,以確保使用者無法向前快轉後續廣告。Then, after the content starts, set playSkippedMedia to true to ensure that users cannot fast-forward through subsequent ads.

注意

Pod 是按順序播放的一組廣告,例如在商業廣告期間播放的一組廣告。A pod is a group of ads that play in a sequence, such as a group of ads that play during a commercial break. 如需詳細資訊,請參閱 IAB 數位視訊廣告服務樣板 (VAST) 規格。For more details, see the IAB Digital Video Ad Serving Template (VAST) specification.

requestTimeoutrequestTimeout

此内容取得或設定媒體必須可播放的毫秒數,以等待逾時之前的廣告要求回應。設定為 0 的值通知系統永遠不要啟動逾時功能。This property gets or sets the number of milliseconds to wait for an ad request response before timing out. A value of 0 informs the system to never timeout. 預設值是 30000 毫秒 (30 秒)。The default is 30000 ms (30 seconds).

scheduleschedule

此屬性取得從廣告伺服器擷取的排程資料。This property gets the schedule data that was retrieved from the ad server. 此物件包含與視訊廣告服務樣板 (VAST) 或視訊多廣告播放列表 (VMAP) 視訊的結構相對應的完整階層資料。This object includes the full hierarchy of data that corresponds to the structure of the Video Ad Serving Template (VAST) or Video Multiple Ad Playlist (VMAP) payload.

onAdProgressonAdProgress

這個事件會在廣告播放達到四分位檢查點時引發。This event is raised when ad playback reaches quartile checkpoints. 事件處理常式 (eventInfo) 的第二個參數是 JSON 物件,其成員如下:The second parameter of the event handler (eventInfo) is a JSON object with the following members:

  • 進行中:廣告播放狀態 (在 AdScheduler.js 中定義的其中一個 MediaProgress 列舉值 )。progress: The ad playback status (one of the MediaProgress enum values defined in AdScheduler.js).
  • 剪輯:正在播放的視訊剪輯。clip: The video clip that is being played. 此物件並不適用於您的代碼。This object is not intended to be used in your code.
  • adPackage:表示與正在播放的廣告相對應的廣告有效承載部分之物件。adPackage: An object that represents the part of the ad payload that corresponds to the ad that is playing. 此物件並不適用於您的代碼。This object is not intended to be used in your code.

onAllCompleteonAllComplete

當主要內容結束時並且任何已排程的影片結束後播放的廣告也結束時,會引發此事件。This event is raised when the main content reaches the end and any scheduled post-roll ads are also ended.

onErrorOccurredonErrorOccurred

AdScheduler 發生錯誤會引發此事件。This event is raised when the AdScheduler encounters an error. 有關錯誤碼值的詳細資訊,請參閱 ErrorCodeFor more information about the error code values, see ErrorCode.

onPodCountdownonPodCountdown

廣告播放時會引發此事件,並指出目前 Pod 的剩餘時間。This event is raised when an ad is playing and indicates how much time remains in the current pod. 事件處理常式 (eventData) 的第二個參數是 JSON 物件,其成員如下:The second parameter of the event handler (eventData) is a JSON object with the following members:

  • remainingAdTime:目前廣告剩餘的秒數。remainingAdTime: The number of seconds left for the current ad.
  • remainingPodTime:目前 Pod 剩餘的秒數。remainingPodTime: The number of seconds left for the current pod.

注意

Pod 是按順序播放的一組廣告,例如在商業廣告期間播放的一組廣告。A pod is a group of ads that play in a sequence, such as a group of ads that play during a commercial break. 如需詳細資訊,請參閱 IAB 數位視訊廣告服務樣板 (VAST) 規格。For more details, see the IAB Digital Video Ad Serving Template (VAST) specification.

onPodEndonPodEnd

Pod 結束時會引發此事件。This event is raised when an ad pod ends. 事件處理常式 (eventData) 的第二個參數是 JSON 物件,其成員如下:The second parameter of the event handler (eventData) is a JSON object with the following members:

  • startTime:Pod 的開始時間 (秒)。startTime: The pod's start time, in seconds.
  • pod:代表 Pod 的物件。pod: An object that represents the pod. 此物件並不適用於您的代碼。This object is not intended to be used in your code.

onPodStartonPodStart

Pod 開始時會引發此事件。This event is raised when an ad pod starts. 事件處理常式 (eventData) 的第二個參數是 JSON 物件,其成員如下:The second parameter of the event handler (eventData) is a JSON object with the following members:

  • startTime:Pod 的開始時間 (秒)。startTime: The pod's start time, in seconds.
  • pod:代表 Pod 的物件。pod: An object that represents the pod. 此物件並不適用於您的代碼。This object is not intended to be used in your code.