教程:基于 URL 对远程文件进行编码并流式传输视频 - RESTTutorial: Encode a remote file based on URL and stream the video - REST

媒体服务徽标 v3media services logo v3


使用 Azure 媒体服务可以将媒体文件编码为可在各种浏览器和设备上播放的格式。Azure Media Services enables you to encode your media files into formats that can be played on a wide variety of browsers and devices. 例如,可能需要以 Apple 的 HLS 或 MPEG DASH 格式流式传输内容。For example, you might want to stream your content in Apple's HLS or MPEG DASH formats. 在流式传输之前,应该对高质量的数字媒体文件进行编码。Before streaming, you should encode your high-quality digital media file. 有关编码指南,请参阅编码概念For encoding guidance, see Encoding concept.

本教程介绍如何使用 REST 通过 Azure 媒体服务基于 URL 对文件进行编码并流式传输视频。This tutorial shows you how to encode a file based on a URL and stream the video with Azure Media Services using REST.

播放视频

本教程演示如何:This tutorial shows you how to:

  • 创建媒体服务帐户Create a Media Services account
  • 访问媒体服务 APIAccess the Media Services API
  • 下载 Postman 文件Download Postman files
  • 配置 PostmanConfigure Postman
  • 使用 Postman 发送请求Send requests using Postman
  • 测试流式 URLTest the streaming URL
  • 清理资源Clean up resources

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

先决条件Prerequisites

  • 创建媒体服务帐户Create a Media Services account.

    请务必记住用于资源组名称和媒体服务帐户名称的值Make sure to remember the values that you used for the resource group name and Media Services account name

  • 安装 Postman REST 客户端,以便执行一些 AMS REST 教程中所示的 REST API。Install the Postman REST client to execute the REST APIs shown in some of the AMS REST tutorials.

    我们使用的是 Postman,但任何 REST 工具都适用。We are using Postman but any REST tool would be suitable. 其他替代工具包括:带有 REST 插件的 Visual Studio CodeTelerik FiddlerOther alternatives are: Visual Studio Code with the REST plugin or Telerik Fiddler.

下载 Postman 文件Download Postman files

克隆包含 Postman 集合和环境文件的 GitHub 存储库。Clone a GitHub repository that contains the Postman collection and environment files.

git clone https://github.com/Azure-Samples/media-services-v3-rest-postman.git

访问 APIAccess API

有关详细信息,请参阅获取访问媒体服务 API 的凭据For detailed information, see Get credentials to access Media Services API

配置 PostmanConfigure Postman

配置环境Configure the environment

  1. 打开 Postman 应用。Open the Postman app.

  2. 在屏幕的右侧,选择“管理环境”选项。On the right of the screen, select the Manage environment option.

    管理环境

  3. 从“管理环境”对话框中,单击“导入”。From the Manage environment dialog, click Import.

  4. 浏览到克隆 https://github.com/Azure-Samples/media-services-v3-rest-postman.git 时下载的 Azure Media Service v3 Environment.postman_environment.json 文件。Browse to the Azure Media Service v3 Environment.postman_environment.json file that was downloaded when you cloned https://github.com/Azure-Samples/media-services-v3-rest-postman.git.

  5. Azure Media Service v3 Environment 环境已添加。The Azure Media Service v3 Environment environment is added.

    备注

    使用从上面的“访问媒体服务 API”部分获得的值更新访问权限变量。Update access variables with values you got from the Access the Media Services API section above.

  6. 双击所选的文件,并输入通过执行访问 API 步骤获得的值。Double-click on the selected file and enter values that you got by following the accessing API steps.

  7. 关闭对话框。Close the dialog.

  8. 从下拉列表中选择“Azure Media Service v3 Environment”环境。Select the Azure Media Service v3 Environment environment from the dropdown.

    选择环境

配置集合Configure the collection

  1. 单击“导入”导入该集合文件。Click Import to import the collection file.

  2. 浏览到克隆 https://github.com/Azure-Samples/media-services-v3-rest-postman.git 时下载的 Media Services v3.postman_collection.json 文件Browse to the Media Services v3.postman_collection.json file that was downloaded when you cloned https://github.com/Azure-Samples/media-services-v3-rest-postman.git

  3. 选择 Media Services v3.postman_collection.json 文件。Choose the Media Services v3.postman_collection.json file.

    导入文件

使用 Postman 发送请求Send requests using Postman

在本部分中,请发送与编码和创建 URL 相关的请求,以便能够流式传输文件。In this section, we send requests that are relevant to encoding and creating URLs so you can stream your file. 具体说来,将发送以下请求:Specifically, the following requests are sent:

  1. 获取适用于服务主体身份验证的 Azure AD 令牌Get Azure AD Token for Service Principal Authentication
  2. 启动流式处理终结点Start a Streaming Endpoint
  3. 创建输出资产Create an output asset
  4. 创建转换Create a Transform
  5. 创建作业Create a Job
  6. 创建流定位符Create a Streaming Locator
  7. 列出流式处理定位符的路径List paths of the Streaming Locator

备注

本教程假定你使用唯一名称创建所有资源。This tutorial assumes you are creating all resources with unique names.

获取 Azure AD 令牌Get Azure AD Token

  1. 在 Postman 应用的左窗口中,选择“步骤 1: 获取 AAD 身份验证令牌”。In the left window of the Postman app, select "Step 1: Get AAD Auth token".

  2. 然后,选择“获取适用于服务主体身份验证的 Azure AD 令牌”。Then, select "Get Azure AD Token for Service Principal Authentication".

  3. 按“发送”。Press Send.

    将会发送以下 POST 操作。The following POST operation is sent.

    https://login.partner.microsoftonline.cn/:tenantId/oauth2/token
    
  4. 响应会返回此令牌并将“AccessToken”环境变量设置为令牌值。The response comes back with the token and sets the "AccessToken" environment variable to the token value. 若要查看设置“AccessToken”的代码,请单击“测试”选项卡。To see the code that sets "AccessToken" , click on the Tests tab.

    获取 AAD 令牌

启动流式处理终结点Start a Streaming Endpoint

若要启用流式处理,必须首先启动要从中流式处理视频的流式处理终结点To enable streaming, you first have to start the Streaming Endpoint from which you want to stream the video.

备注

仅当流式处理终结点处于运行状态时才进行计费。You are only billed when your Streaming Endpoint is in the running state.

  1. 在 Postman 应用的左侧窗口中,选择“流式处理和实时”。In the left window of the Postman app, select "Streaming and Live".

  2. 然后,选择“启动 StreamingEndpoint”。Then, select "Start StreamingEndpoint".

  3. 按“发送”。Press Send.

    • 发送以下 POST 操作:The following POST operation is sent:

      https://management.chinacloudapi.cn/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Media/mediaservices/:accountName/streamingEndpoints/:streamingEndpointName/start?api-version={{api-version}}
      
    • 如果请求成功,则返回 Status: 202 AcceptedIf the request is successful, the Status: 202 Accepted is returned.

      此状态表示已接受请求进行处理;但是,处理尚未完成。This status means that the request has been accepted for processing; however, the processing has not been completed. 可以根据 Azure-AsyncOperation 响应标头中的值查询操作状态。You can query for the operation status based on the value in the Azure-AsyncOperation response header.

      例如,下面的 GET 操作返回操作的状态:For example, the following GET operation returns the status of your operation:

      https://management.chinacloudapi.cn/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/<resourceGroupName>/providers/Microsoft.Media/mediaservices/<accountName>/streamingendpointoperations/1be71957-4edc-4f3c-a29d-5c2777136a2e?api-version=2018-07-01

      跟踪异步 Azure 操作一文深入说明了如何通过响应中返回的值跟踪异步 Azure 操作的状态。The track asynchronous Azure operations article explains in depth how to track the status of asynchronous Azure operations through values returned in the response.

创建输出资产Create an output asset

输出资产会存储作业编码的结果。The output Asset stores the result of your encoding job.

  1. 在 Postman 应用的左侧窗口中,选择“资产”。In the left window of the Postman app, select "Assets".

  2. 然后选择“创建或更新资产”。Then, select "Create or update an Asset".

  3. 按“发送”。Press Send.

    • 将会发送以下 PUT 操作:The following PUT operation is sent:

      https://management.chinacloudapi.cn/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Media/mediaServices/:accountName/assets/:assetName?api-version={{api-version}}
      
    • 该操作具有以下正文:The operation has the following body:

      {
      "properties": {
          "description": "My Asset",
          "alternateId" : "some GUID"
       }
      }
      

创建转换Create a transform

对媒体服务中的内容进行编码或处理时,一种常见的模式是将编码设置设为脚本。When encoding or processing content in Media Services, it is a common pattern to set up the encoding settings as a recipe. 然后,需提交作业,将该脚本应用于视频。You would then submit a Job to apply that recipe to a video. 为每个新视频提交新作业后,可将该脚本应用到库中的所有视频。By submitting new jobs for each new video, you are applying that recipe to all the videos in your library. 媒体服务中的脚本称为转换A recipe in Media Services is called as a Transform. 有关详细信息,请参阅转换和作业For more information, see Transforms and Jobs. 本教程中的示例定义有关将视频进行编码以将其流式传输到各种 iOS 和 Android 设备的脚本。The sample described in this tutorial defines a recipe that encodes the video in order to stream it to a variety of iOS and Android devices.

创建新实例时,需要指定希望生成的输出内容转换When creating a new Transform instance, you need to specify what you want it to produce as an output. 所需参数是 TransformOutput 对象。The required parameter is a TransformOutput object. 每个 TransformOutput 包含一个预设 。Each TransformOutput contains a Preset. 预设介绍了视频和/或音频处理操作的分步说明,这些操作将用于生成所需的 TransformOutput 。Preset describes the step-by-step instructions of video and/or audio processing operations that are to be used to generate the desired TransformOutput. 本文中的示例使用名为 AdaptiveStreaming 的内置预设。The sample described in this article uses a built-in Preset called AdaptiveStreaming. 此预设将输入的视频编码为基于输入的分辨率和比特率自动生成的比特率阶梯(比特率 - 分辨率对),并通过与每个比特率 - 分辨率对相对应的 H.264 视频和 AAC 音频生成 ISO MP4 文件。The Preset encodes the input video into an auto-generated bitrate ladder (bitrate-resolution pairs) based on the input resolution and bitrate, and produces ISO MP4 files with H.264 video and AAC audio corresponding to each bitrate-resolution pair. 有关此预设的信息,请参阅自动生成比特率阶梯For information about this Preset, see auto-generating bitrate ladder.

可以使用内置 EncoderNamedPreset 或使用自定义预设。You can use a built-in EncoderNamedPreset or use custom presets.

备注

在创建转换时,首先应检查是否已存在一个使用 Get 方法的转换。When creating a Transform, you should first check if one already exists using the Get method. 本教程假定你使用唯一名称创建该转换。This tutorial assumes you are creating the transform with a unique name.

  1. 在 Postman 应用的左侧窗口中,选择“编码和分析”。In the left window of the Postman app, select "Encoding and Analysis".

  2. 然后选择“创建转换”。Then, select "Create Transform".

  3. 按“发送”。Press Send.

    • 将会发送以下 PUT 操作。The following PUT operation is sent.

      https://management.chinacloudapi.cn/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Media/mediaServices/:accountName/transforms/:transformName?api-version={{api-version}}
      
    • 该操作具有以下正文:The operation has the following body:

      {
          "properties": {
              "description": "Standard Transform using an Adaptive Streaming encoding preset from the library of built-in Standard Encoder presets",
              "outputs": [
                  {
                  "onError": "StopProcessingJob",
              "relativePriority": "Normal",
                  "preset": {
                      "@odata.type": "#Microsoft.Media.BuiltInStandardEncoderPreset",
                      "presetName": "AdaptiveStreaming"
                  }
                  }
              ]
          }
      }
      

创建作业Create a job

作业是针对媒体服务的实际请求,目的是将创建的转换应用到给定的输入视频或音频内容。A Job is the actual request to Media Services to apply the created Transform to a given input video or audio content. 作业指定输入视频位置和输出位置等信息。The Job specifies information like the location of the input video, and the location for the output.

在此示例中,作业的输入基于 HTTPS URL(“https://nimbuscdn-nimbuspm.streaming.mediaservices.windows.net/2b533311-b215-4409-80af-529c3e853622/”)。In this example, the job's input is based on an HTTPS URL ("https://nimbuscdn-nimbuspm.streaming.mediaservices.windows.net/2b533311-b215-4409-80af-529c3e853622/").

  1. 在 Postman 应用的左侧窗口中,选择“编码和分析”。In the left window of the Postman app, select "Encoding and Analysis".

  2. 然后选择“创建或更新作业”。Then, select "Create or Update Job".

  3. 按“发送”。Press Send.

    • 将会发送以下 PUT 操作。The following PUT operation is sent.

      https://management.chinacloudapi.cn/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Media/mediaServices/:accountName/transforms/:transformName/jobs/:jobName?api-version={{api-version}}
      
    • 该操作具有以下正文:The operation has the following body:

      {
      "properties": {
          "input": {
          "@odata.type": "#Microsoft.Media.JobInputHttp",
          "baseUri": "https://nimbuscdn-nimbuspm.streaming.mediaservices.windows.net/2b533311-b215-4409-80af-529c3e853622/",
          "files": [
                  "Ignite-short.mp4"
              ]
          },
          "outputs": [
          {
              "@odata.type": "#Microsoft.Media.JobOutputAsset",
              "assetName": "testAsset1"
          }
          ]
      }
      }
      

此作业需要一些时间才能完成,完成时可发出通知。The job takes some time to complete and when it does you want to be notified. 若要查看作业的进度,建议使用事件网格。To see the progress of the job, we recommend using Event Grid. 事件网格旨在实现高可用性、一致性能和动态缩放。It is designed for high availability, consistent performance, and dynamic scale. 使用事件网格,应用可以侦听和响应来自几乎所有 Azure 服务和自定义源的事件。With Event Grid, your apps can listen for and react to events from virtually all Azure services, as well as custom sources. 处理基于 HTTP 的反应事件非常简单,这有助于通过对事件的智能筛选和路由生成高效的解决方案。Simple, HTTP-based reactive event handling helps you build efficient solutions through intelligent filtering and routing of events. 请参阅将事件路由到自定义 Web 终结点See Route events to a custom web endpoint.

作业通常会经历以下状态:已计划已排队正在处理已完成(最终状态)。The Job usually goes through the following states: Scheduled, Queued, Processing, Finished (the final state). 如果作业出错,则显示“错误”状态。If the job has encountered an error, you get the Error state. 如果作业正处于取消过程中,则显示“正在取消”,完成时则显示“已取消” 。If the job is in the process of being canceled, you get Canceling and Canceled when it is done.

作业错误代码Job error codes

请参阅错误代码See Error codes.

创建流式处理定位符Create a streaming locator

编码作业完成后,下一步是使输出资产中的视频可供客户端播放。After the encoding job is complete, the next step is to make the video in the output Asset available to clients for playback. 可通过两个步骤完成此操作:首先,创建 StreamingLocator,然后,生成客户端可以使用的流式 URL。You can accomplish this in two steps: first, create a StreamingLocator, and second, build the streaming URLs that clients can use.

创建流定位符的过程称为发布。The process of creating a streaming locator is called publishing. 默认情况下,除非配置可选的开始和结束时间,否则调用 API 后,流定位符立即生效,并持续到被删除为止。By default, the streaming locator is valid immediately after you make the API calls, and lasts until it is deleted, unless you configure the optional start and end times.

创建 StreamingLocator 时,需要指定所需的 StreamingPolicyNameWhen creating a StreamingLocator, you need to specify the desired StreamingPolicyName. 在此示例中将流式传输明文(或未加密)内容,因此使用预定义的明文流式传输策略“Predefined_ClearStreamingOnly”。In this example, you will be streaming in-the-clear (or non-encrypted) content, so the predefined clear streaming policy "Predefined_ClearStreamingOnly" is used.

重要

使用自定义的 StreamingPolicy 时,应为媒体服务帐户设计有限的一组此类策略,并在需要同样的加密选项和协议时重新将这些策略用于 StreamingLocators。When using a custom StreamingPolicy, you should design a limited set of such policies for your Media Service account, and re-use them for your StreamingLocators whenever the same encryption options and protocols are needed.

媒体服务帐户具有对应于流式处理策略条目数的配额。Your Media Service account has a quota for the number of Streaming Policy entries. 不应为每个流式处理定位符创建新的流式处理策略。You should not be creating a new Streaming Policy for each streaming locator.

  1. 在 Postman 应用的左侧窗口中,选择“流式处理策略和定位符”。In the left window of the Postman app, select "Streaming Policies and Locators".

  2. 然后选择“创建流式处理定位符(清除)”。Then, select "Create a Streaming Locator (clear)".

  3. 按“发送”。Press Send.

    • 将会发送以下 PUT 操作。The following PUT operation is sent.

      https://management.chinacloudapi.cn/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Media/mediaServices/:accountName/streamingLocators/:streamingLocatorName?api-version={{api-version}}
      
    • 该操作具有以下正文:The operation has the following body:

      {
        "properties": {
          "streamingPolicyName": "Predefined_ClearStreamingOnly",
          "assetName": "testAsset1",
          "contentKeys": [],
          "filters": []
       }
      }
      

列出路径和生成流式处理 URLList paths and build streaming URLs

列出路径List paths

创建流式处理定位符后,即可获取流式处理 URLNow that the Streaming Locator has been created, you can get the streaming URLs

  1. 在 Postman 应用的左侧窗口中,选择“流式处理策略”。In the left window of the Postman app, select "Streaming Policies".

  2. 然后,选择“列出路径”。Then, select "List Paths".

  3. 按“发送”。Press Send.

    • 将会发送以下 POST 操作。The following POST operation is sent.

      https://management.chinacloudapi.cn/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Media/mediaServices/:accountName/streamingLocators/:streamingLocatorName/listPaths?api-version={{api-version}}
      
    • 该操作没有正文:The operation has no body:

  4. 记下要用于流式处理的某个路径,以便在下一部分使用。Note one of the paths you want to use for streaming, you will use it in the next section. 在这种情况下,返回以下路径:In this case, the following paths were returned:

    "streamingPaths": [
        {
            "streamingProtocol": "Hls",
            "encryptionScheme": "NoEncryption",
            "paths": [
                "/cdb80234-1d94-42a9-b056-0eefa78e5c63/Ignite-short.ism/manifest(format=m3u8-aapl)"
            ]
        },
        {
            "streamingProtocol": "Dash",
            "encryptionScheme": "NoEncryption",
            "paths": [
                "/cdb80234-1d94-42a9-b056-0eefa78e5c63/Ignite-short.ism/manifest(format=mpd-time-csf)"
            ]
        },
        {
            "streamingProtocol": "SmoothStreaming",
            "encryptionScheme": "NoEncryption",
            "paths": [
                "/cdb80234-1d94-42a9-b056-0eefa78e5c63/Ignite-short.ism/manifest"
            ]
        }
    ]
    

生成流式处理 URLBuild the streaming URLs

在此部分,请生成 HLS 流式处理 URL。In this section, let's build an HLS streaming URL. URL 包含以下值:URLs consist of the following values:

  1. 发送数据时采用的协议。The protocol over which data is sent. 在此示例中为“https”。In this case "https".

    备注

    如果播放器在 Https 站点上进行托管,请确保将 URL 更新为“https”。If a player is hosted on an https site, make sure to update the URL to "https".

  2. StreamingEndpoint 的主机名。StreamingEndpoint's hostname. 在本例中,该名称为“amsaccount-cne21.streaming.media.chinacloudapi.cn”。In this case, the name is "amsaccount-cne21.streaming.media.chinacloudapi.cn".

    若要获取主机名,可以使用以下 GET 操作:To get the hostname, you can use the following GET operation:

    https://management.chinacloudapi.cn/subscriptions/00000000-0000-0000-0000-0000000000000/resourceGroups/amsResourceGroup/providers/Microsoft.Media/mediaservices/amsaccount/streamingEndpoints/default?api-version={{api-version}}
    
  3. 在前面的(列出路径)部分中获得的路径。A path that you got in the previous (List paths) section.

因此,生成了以下 HLS URLAs a result, the following HLS URL was built

https://amsaccount-cne21.streaming.media.chinacloudapi.cn/cdb80234-1d94-42a9-b056-0eefa78e5c63/Ignite-short.ism/manifest(format=m3u8-aapl)

测试流式 URLTest the streaming URL

备注

确保要从中进行流式传输的流式处理终结点正在运行。Make sure the Streaming Endpoint from which you want to stream is running.

本文使用 Azure Media Player 测试流式传输。To test the stream, this article uses Azure Media Player.

  1. 打开 Web 浏览器并导航到 https://aka.ms/azuremediaplayer/Open a web browser and navigate to https://aka.ms/azuremediaplayer/.
  2. 在“URL:”框中,粘贴生成的 URL。In the URL: box, paste the URL you built.
  3. 按“更新播放器”。Press Update Player.

Azure Media Player 可用于测试,但不可在生产环境中使用。Azure Media Player can be used for testing but should not be used in a production environment.

清理媒体服务帐户中的资源Clean up resources in your Media Services account

通常情况下,除了打算重复使用的对象,应清理所有内容(通常会重复使用转换并保留流式处理定位符等)。Generally, you should clean up everything except objects that you are planning to reuse (typically, you will reuse Transforms, and you will persist Streaming Locators, etc.). 如果希望帐户在试验后保持干净状态,则应删除不打算重复使用的资源。If you want for your account to be clean after experimenting, you should delete the resources that you do not plan to reuse.

若要删除资源,请在要删除的任意资源下选择“删除...”操作。To delete a resource, select "Delete ..." operation under whichever resource you want to delete.

清理资源Clean up resources

如果不再需要资源组中的任何一个资源(包括为本教程创建的媒体服务和存储帐户),请删除之前创建的资源组。If you no longer need any of the resources in your resource group, including the Media Services and storage accounts you created for this tutorial, delete the resource group you created earlier.

执行以下 CLI 命令:Execute the following CLI command:

az group delete --name amsResourceGroup