在视频内容中显示广告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

本演练演示了如何在使用 JavaScript 与 HTML 编写的通用 Windows 平台 (UWP) 应用中,使用 AdScheduler 类在视频内容中显示广告。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 应用支持。This feature is currently supported only for UWP apps that are written using JavaScript with HTML.

AdScheduler 同时适用于渐进式和流媒体,并使用 IAB 标准的视频广告服务模板 (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.

视频内容的广告根据程序短于十分钟(简短形式)还是长于十分钟(较长形式)而有所不同。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 广告 SDK 或更高版本。Install 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 Advertising 库的引用。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. 将对适用于 JavaScript 的 Microsoft 广告 SDK 库的引用添加到你的项目。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、单击扩展,然后选中适用于 JavaScript 的 Microsoft 广告 SDK(版本 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> 部分中,在项目的 JavaScript 引用 default.css 和 main.js 之后,添加对 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>
    

    备注

    在包含了 main.js 之后,此行必须放置在 <head> 部分;否则,当你生成项目时将遇到错误。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 代表已向你提供的应用程序 ID 和广告单元 ID。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.

      此方法采用 Promise形式,这是一个异步构造,在其中传递两个函数指针:一个是 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

此属性获取或设置 Boolean 值,用于指示当用户跳到超过计划开始时间的点时,是否播放计划的媒体。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. 允许最终用户随意跳过广告荚。Allow end-users to skip over advertisement pods at will.
  2. 允许用户跳过广告荚,但播放恢复时播放最新的广告荚。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.
  • 一旦一个广告荚开始播放,其中的所有广告都要播放。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.

备注

一个广告荚是一组按顺序播放的广告,如在商业广告时段播放的一组广告。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:

  • progress:广告播放状态(AdScheduler.js 中定义的 MediaProgress 枚举值之一)。progress: The ad playback status (one of the MediaProgress enum values defined in AdScheduler.js).
  • clip:正在播放的视频剪辑。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. 有关错误代码值的详细信息,请参阅错误代码For more information about the error code values, see ErrorCode.

onPodCountdownonPodCountdown

当广告正在播放时触发此事件并指示当前广告荚剩余时间。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:当前广告荚的剩余秒数。remainingPodTime: The number of seconds left for the current 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

广告荚结束时引发此事件。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:广告荚的开始时间(以秒计)。startTime: The pod's start time, in seconds.
  • pod:代表广告荚的对象。pod: An object that represents the pod. 此对象不适用于你的代码。This object is not intended to be used in your code.

onPodStartonPodStart

广告荚开始时引发此事件。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:广告荚的开始时间(以秒计)。startTime: The pod's start time, in seconds.
  • pod:代表广告荚的对象。pod: An object that represents the pod. 此对象不适用于你的代码。This object is not intended to be used in your code.