使用 .NET SDK 开始传送点播内容Get started with delivering content on demand using .NET SDK

媒体服务徽标media services logo

本教程介绍了在 Azure 媒体服务 .NET SDK 中使用 Azure 媒体服务 (AMS) 应用程序实施基本的视频点播 (VoD) 内容传送服务的步骤。This tutorial walks you through the steps of implementing a basic Video-on-Demand (VoD) content delivery service with Azure Media Services (AMS) application using the Azure Media Services .NET SDK.


以下是完成本教程所需具备的条件:The following are required to complete the tutorial:

本教程包括以下任务:This tutorial includes the following tasks:

  1. 启动流式处理终结点(使用 Azure 门户)。Start streaming endpoint (using the Azure portal).
  2. 创建和配置 Visual Studio 项目。Create and configure a Visual Studio project.
  3. 连接到媒体服务帐户。Connect to the Media Services account.
  4. 上传视频文件。Upload a video file.
  5. 将源文件编码为一组自适应比特率 MP4 文件。Encode the source file into a set of adaptive bitrate MP4 files.
  6. 发布资产并获取流式处理和渐进式下载 URL。Publish the asset and get streaming and progressive download URLs.
  7. 播放内容。Play your content.


本教程将引导你完成使用用于 .NET 的 Azure 媒体服务 (AMS) SDK 实施视频点播 (VoD) 内容传送应用程序的步骤。This tutorial walks you through the steps of implementing a Video-on-Demand (VoD) content delivery application using Azure Media Services (AMS) SDK for .NET.

本教程介绍了基本的媒体服务工作流,以及进行媒体服务开发需要用到的最常见编程对象和任务。The tutorial introduces the basic Media Services workflow and the most common programming objects and tasks required for Media Services development. 完成本教程后,就可以流式传输或渐进下载已上传、编码和下载的示例媒体文件。At the completion of the tutorial, you will be able to stream or progressively download a sample media file that you uploaded, encoded, and downloaded.

AMS 模型AMS model

开发针对媒体服务 OData 模型的 VoD 应用程序时,以下图像会显示某些最常用的对象。The following image shows some of the most commonly used objects when developing VoD applications against the Media Services OData model.

单击图像查看其完整大小。Click the image to view it full size.

显示用于开发点播视频应用程序的 Azure 媒体服务对象数据模型中一些最常用对象的关系图。Diagram showing some of the most commonly used objects in the Azure Media Services object data model for developing Video on Demand applications.

可在 此处查看完整模型。You can view the whole model here.

使用 Azure 门户启动流式处理终结点Start streaming endpoints using the Azure portal

使用 Azure 媒体服务时,最常见的场景之一是通过自适应比特率流式处理传送视频。When working with Azure Media Services one of the most common scenarios is delivering video via adaptive bitrate streaming. 媒体服务提供动态打包,可按媒体服务支持的流格式(MPEG DASH、HLS、平滑流式处理)及时传送自适应比特率 MP4 编码内容,而无需存储上述各种流格式的预打包版本。Media Services provides dynamic packaging, which allows you to deliver your adaptive bitrate MP4 encoded content in streaming formats supported by Media Services (MPEG DASH, HLS, Smooth Streaming) just-in-time, without you having to store pre-packaged versions of each of these streaming formats.


创建 AMS 帐户后,会将一个处于“已停止”状态的默认流式处理终结点添加到帐户。When your AMS account is created a default streaming endpoint is added to your account in the Stopped state. 若要开始流式传输内容并利用动态打包和动态加密,要从中流式传输内容的流式处理终结点必须处于“正在运行”状态。To start streaming your content and take advantage of dynamic packaging and dynamic encryption, the streaming endpoint from which you want to stream content has to be in the Running state.

若要启动流式处理终结点,请执行以下操作:To start the streaming endpoint, do the following:

  1. Azure 门户登录。Log in at the Azure portal.

  2. 在“设置”窗口中,单击“流式处理终结点”。In the Settings window, click Streaming endpoints.

  3. 单击默认的流式处理终结点。Click the default streaming endpoint.

    此时会显示“默认流式处理终结点详细信息”窗口。The DEFAULT STREAMING ENDPOINT DETAILS window appears.

  4. 单击“启动”图标。Click the Start icon.

  5. 单击“保存”按钮保存更改。Click the Save button to save your changes.

创建和配置 Visual Studio 项目Create and configure a Visual Studio project

  1. 设置开发环境,并在 app.config 文件中填充连接信息,如使用 .NET 进行媒体服务开发中所述。Set up your development environment and populate the app.config file with connection information, as described in Media Services development with .NET.
  2. 创建新的文件夹(文件夹可以位于本地驱动器上的任何位置),并复制需要编码和流处理或渐进式下载的 .mp4 文件。Create a new folder (folder can be anywhere on your local drive) and copy an .mp4 file that you want to encode and stream or progressively download. 在此示例中,我们使用了“C:\VideoFiles”路径。In this example, the "C:\VideoFiles" path is used.

连接到媒体服务帐户Connect to the Media Services account

使用采用 .NET 的媒体服务时,必须将 CloudMediaContext 类用于大多数媒体服务编程任务:连接到媒体服务帐户;创建、更新、访问和删除以下对象:资产、资产文件、作业、访问策略、定位符等等。When using Media Services with .NET, you must use the CloudMediaContext class for most Media Services programming tasks: connecting to Media Services account; creating, updating, accessing, and deleting the following objects: assets, asset files, jobs, access policies, locators, etc.

使用以下代码覆盖默认的 Program 类:此代码演示如何从 App.config 文件中读取连接值,以及如何创建 CloudMediaContext 对象以连接到媒体服务。Overwrite the default Program class with the following code: The code demonstrates how to read the connection values from the App.config file and how to create the CloudMediaContext object in order to connect to Media Services. 有关详细信息,请参阅连接到媒体服务 APIFor more information, see connecting to the Media Services API.

确保更新保存媒体文件所需的文件名和路径。Make sure to update the file name and path to where you have your media file.

Main 函数调用会在本部分中进一步定义的方法。The Main function calls methods that will be defined further in this section.


会收到编译错误,直到为所有在本文后面部分进行定义的函数添加定义为止。You will be getting compilation errors until you add definitions for all the functions that are defined later in this article.

    class Program
        // Read values from the App.config file.
        private static readonly string _AADTenantDomain =
        private static readonly string _RESTAPIEndpoint =
        private static readonly string _AMSClientId =
        private static readonly string _AMSClientSecret =

        private static CloudMediaContext _context = null;

        static void Main(string[] args)
            AzureAdTokenCredentials tokenCredentials = 
                new AzureAdTokenCredentials(_AADTenantDomain,
                    new AzureAdClientSymmetricKey(_AMSClientId, _AMSClientSecret),

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider);

            // Add calls to methods defined in this section.
            // Make sure to update the file name and path to where you have your media file.
            IAsset inputAsset =
            UploadFile(@"C:\VideoFiles\BigBuckBunny.mp4", AssetCreationOptions.None);

            IAsset encodedAsset =
            EncodeToAdaptiveBitrateMP4s(inputAsset, AssetCreationOptions.None);

        catch (Exception exception)
            // Parse the XML error message in the Media Services response and create a new
            // exception with its content.
            exception = MediaServicesExceptionParser.Parse(exception);


创建新资产并上传视频文件Create a new asset and upload a video file

在媒体服务中,可以将数字文件上传(引入)到资产中。In Media Services, you upload (or ingest) your digital files into an asset. “资产”实体可以包含视频、音频、图片、缩略图集合、文本曲目和隐藏式字幕文件(以及这些文件的相关元数据。)上传文件完成后,相关内容即安全地存储在云中供后续处理和流式处理。The Asset entity can contain video, audio, images, thumbnail collections, text tracks, and closed caption files (and the metadata about these files.) Once the files are uploaded, your content is stored securely in the cloud for further processing and streaming. 资产中的文件称为 资产文件The files in the asset are called Asset Files.

下面定义的 UploadFile 方法调用 CreateFromFile(在 .NET SDK Extensions 中定义)。The UploadFile method defined below calls CreateFromFile (defined in .NET SDK Extensions). CreateFromFile 创建指定的源文件所要上传到的新资产。CreateFromFile creates a new asset into which the specified source file is uploaded.

CreateFromFile 方法采用 AssetCreationOptions,后者用于指定以下任一资产创建选项:The CreateFromFile method takes AssetCreationOptions, which lets you specify one of the following asset creation options:

  • - 不使用加密。None - No encryption is used. 这是默认值。This is the default value. 请注意,使用此选项时,内容在传送过程中或静态存储过程中都不会受到保护。Note that when using this option, your content is not protected in transit or at rest in storage. 如果计划使用渐进式下载交付 MP4,则使用此选项。If you plan to deliver an MP4 using progressive download, use this option.
  • StorageEncrypted - 使用此选项可以通过高级加密标准 (AES) 256 位加密在本地加密明文内容,然后将其上传到 Azure 存储中以加密形式静态存储相关内容。StorageEncrypted - Use this option to encrypt your clear content locally using Advanced Encryption Standard (AES)-256 bit encryption, which then uploads it to Azure Storage where it is stored encrypted at rest. 受存储加密保护的资产会在编码前自动解密并放入经过加密的文件系统中,并可选择在重新上传为新的输出资产前重新加密。Assets protected with Storage Encryption are automatically unencrypted and placed in an encrypted file system prior to encoding, and optionally re-encrypted prior to uploading back as a new output asset. 存储加密的主要用例是在磁盘上通过静态增强加密来保护高品质的输入媒体文件。The primary use case for Storage Encryption is when you want to secure your high-quality input media files with strong encryption at rest on disk.
  • CommonEncryptionProtected - 上传经过通用加密或 PlayReady DRM 加密并受其保护的内容(例如,受 PlayReady DRM 保护的平滑流)时使用此选项。CommonEncryptionProtected - Use this option if you are uploading content that has already been encrypted and protected with Common Encryption or PlayReady DRM (for example, Smooth Streaming protected with PlayReady DRM).
  • EnvelopeEncryptionProtected - 如果要上传使用 AES 加密的 HLS,请使用此选项。EnvelopeEncryptionProtected – Use this option if you are uploading HLS encrypted with AES. 请注意,Transform Manager 必须已对文件进行编码和加密。Note that the files must have been encoded and encrypted by Transform Manager.

CreateFromFile 方法还允许指定回调,以报告文件的上传进度。The CreateFromFile method also lets you specify a callback in order to report the upload progress of the file.

在以下示例中,指定了 None 作为资产选项。In the following example, we specify None for the asset options.

将以下方法添加到 Program 类。Add the following method to the Program class.

    static public IAsset UploadFile(string fileName, AssetCreationOptions options)
        IAsset inputAsset = _context.Assets.CreateFromFile(
            (af, p) =>
                Console.WriteLine("Uploading '{0}' - Progress: {1:0.##}%", af.Name, p.Progress);

        Console.WriteLine("Asset {0} created.", inputAsset.Id);

        return inputAsset;

将源文件编码为一组自适应比特率 MP4 文件Encode the source file into a set of adaptive bitrate MP4 files

将资产引入媒体服务后,即可对媒体进行编码、传输复用、打水印等处理,然后将其传送至客户端。After ingesting assets into Media Services, media can be encoded, transmuxed, watermarked, and so on, before it is delivered to clients. 将根据多个后台角色实例调度把那个运行这些活动,以确保较高的性能和可用性。These activities are scheduled and run against multiple background role instances to ensure high performance and availability. 这些活动称为作业,每个作业由原子任务构成,这些原子任务在资产文件上完成具体的工作。These activities are called Jobs, and each Job is composed of atomic Tasks that do the actual work on the Asset file.

如前所述,使用 Azure 媒体服务时最常见的方案之一是将自适应比特率流传送至客户端。As was mentioned earlier, when working with Azure Media Services, one of the most common scenarios is delivering adaptive bitrate streaming to your clients. 媒体服务可以将一组自适应比特率 MP4 文件动态打包为以下其中一种格式:HTTP Live Streaming (HLS)、平滑流式处理和 MPEG DASH。Media Services can dynamically package a set of adaptive bitrate MP4 files into one of the following formats: HTTP Live Streaming (HLS), Smooth Streaming, and MPEG DASH.

要利用动态打包,需将夹层(源)文件编码或转换成一组自适应比特率 MP4 文件或自适应比特率平滑流文件。To take advantage of dynamic packaging, you need to encode or transcode your mezzanine (source) file into a set of adaptive bitrate MP4 files or adaptive bitrate Smooth Streaming files.

以下代码演示如何提交编码作业。The following code shows how to submit an encoding job. 该作业所包含的一项任务会指定要使用 Media Encoder Standard将夹层文件转码成一组自适应比特率 MP4。The job contains one task that specifies to transcode the mezzanine file into a set of adaptive bitrate MP4s using Media Encoder Standard. 代码会提交作业,并等待作业完成。The code submits the job and waits until it is completed.

作业完成后,即可流式处理资产,或渐进式下载转码后所创建的 MP4 文件。Once the job is completed, you would be able to stream your asset or progressively download MP4 files that were created as a result of transcoding.

将以下方法添加到 Program 类。Add the following method to the Program class.

    static public IAsset EncodeToAdaptiveBitrateMP4s(IAsset asset, AssetCreationOptions options)

        // Prepare a job with a single task to transcode the specified asset
        // into a multi-bitrate asset.

        IJob job = _context.Jobs.CreateWithSingleTask(
            "Media Encoder Standard",
            "Adaptive Streaming",
            "Adaptive Bitrate MP4",

        Console.WriteLine("Submitting transcoding job...");

        // Submit the job and wait until it is completed.

        job = job.StartExecutionProgressTask(
            j =>
                Console.WriteLine("Job state: {0}", j.State);
                Console.WriteLine("Job progress: {0:0.##}%", j.GetOverallProgress());

        Console.WriteLine("Transcoding job finished.");

        IAsset outputAsset = job.OutputMediaAssets[0];

        return outputAsset;

发布资产并获取用于流式处理和渐进式下载的 URLPublish the asset and get URLs for streaming and progressive download

要流处理或下载资产,必须先创建定位符来“发布”资产。To stream or download an asset, you first need to "publish" it by creating a locator. 定位符提供对资产中所含文件的访问权限。Locators provide access to files contained in the asset. 媒体服务支持两种类型的定位符:用于流媒体(例如,MPEG DASH、HLS 或平滑流式处理)的 OnDemandOrigin 定位符,以及用于下载媒体文件的访问签名 (SAS) 定位符。Media Services supports two types of locators: OnDemandOrigin locators, used to stream media (for example, MPEG DASH, HLS, or Smooth Streaming) and Access Signature (SAS) locators, used to download media files.

有关 URL 格式的一些详细信息Some details about URL formats

创建定位符后,可以生成用来流式处理或下载文件的 URL。After you create the locators, you can build the URLs that would be used to stream or download your files. 本教程中的示例会输出 URL,可以将其粘贴在适当的浏览器中。The sample in this tutorial outputs URLs that you can paste in appropriate browsers. 此部分直接提供了多个简短的示例,介绍了各种不同的格式。This section just gives short examples of what different formats look like.

MPEG DASH 的流 URL 采用以下格式:A streaming URL for MPEG DASH has the following format:

{流式处理终结点名称-媒体服务帐户名称}.streaming.mediaservices.chinacloudapi.cn/{定位符 ID}/{文件名}.ism/Manifest (format=mpd-time-csf){streaming endpoint name-media services account name}.streaming.mediaservices.chinacloudapi.cn/{locator ID}/{filename}.ism/Manifest (format=mpd-time-csf)

HLS 的流 URL 采用以下格式:A streaming URL for HLS has the following format:

{流式处理终结点名称-媒体服务帐户名称}.streaming.mediaservices.chinacloudapi.cn/{定位符 ID}/{文件名}.ism/Manifest (format=m3u8-aapl){streaming endpoint name-media services account name}.streaming.mediaservices.chinacloudapi.cn/{locator ID}/{filename}.ism/Manifest (format=m3u8-aapl)

平滑流式处理的流式处理 URL 采用以下格式:A streaming URL for Smooth Streaming has the following format:

{流式处理终结点名称-媒体服务帐户名称}.streaming.mediaservices.chinacloudapi.cn/{定位符 ID}/{文件名}.ism/Manifest{streaming endpoint name-media services account name}.streaming.mediaservices.chinacloudapi.cn/{locator ID}/{filename}.ism/Manifest

用于下载文件的 SAS URL 采用以下格式:A SAS URL used to download files has the following format:

{blob 容器名称}/{资产名称}/{文件名}/{SAS 签名}{blob container name}/{asset name}/{file name}/{SAS signature}

媒体服务.NET SDK 扩展提供了便利的帮助器方法,可针对已发布的资产返回格式化 URL。Media Services .NET SDK extensions provide convenient helper methods that return formatted URLs for the published asset.

以下代码使用 .NET SDK 扩展创建定位符,获取流和渐进式下载 URL。The following code uses .NET SDK Extensions to create locators and to get streaming and progressive download URLs. 该代码还演示了如何将文件下载到本地文件夹。The code also shows how to download files to a local folder.

将以下方法添加到 Program 类。Add the following method to the Program class.

    static public void PublishAssetGetURLs(IAsset asset)
        // Publish the output asset by creating an Origin locator for adaptive streaming,
        // and a SAS locator for progressive download.



        IEnumerable<IAssetFile> mp4AssetFiles = asset
                .Where(af => af.Name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase));

        // Get the Smooth Streaming, HLS and MPEG-DASH URLs for adaptive streaming,
        // and the Progressive Download URL.
        Uri smoothStreamingUri = asset.GetSmoothStreamingUri();
        Uri hlsUri = asset.GetHlsUri();
        Uri mpegDashUri = asset.GetMpegDashUri();

        // Get the URls for progressive download for each MP4 file that was generated as a result
        // of encoding.
        List<Uri> mp4ProgressiveDownloadUris = mp4AssetFiles.Select(af => af.GetSasUri()).ToList();

        // Display  the streaming URLs.
        Console.WriteLine("Use the following URLs for adaptive streaming: ");

        // Display the URLs for progressive download.
        Console.WriteLine("Use the following URLs for progressive download.");
        mp4ProgressiveDownloadUris.ForEach(uri => Console.WriteLine(uri + "\n"));

        // Download the output asset to a local folder.
        string outputFolder = "job-output";
        if (!Directory.Exists(outputFolder))

        Console.WriteLine("Downloading output asset files to a local folder...");
            (af, p) =>
                Console.WriteLine("Downloading '{0}' - Progress: {1:0.##}%", af.Name, p.Progress);

        Console.WriteLine("Output asset files available at '{0}'.", Path.GetFullPath(outputFolder));

通过播放内容进行测试Test by playing your content

在执行上一部分中定义的程序后,控制台窗口中会显示如下所示的 URL。Once you run the program defined in the previous section, the URLs similar to the following will be displayed in the console window.

自适应流式处理 URL:Adaptive streaming URLs:

平滑流Smooth Streaming






渐进式下载 URL(音频和视频)。Progressive download URLs (audio and video).









要流式传输视频,请将 URL 粘贴到 Azure 媒体服务播放器的 URL 文本框中。To stream your video, paste your URL in the URL textbox in the Azure Media Services Player.

要测试渐进式下载,请将 URL 粘贴到浏览器(例如 Internet Explorer、Chrome 或 Safari)中。To test progressive download, paste a URL into a browser (for example, Internet Explorer, Chrome, or Safari).

有关详细信息,请参阅下列主题:For more information, see the following topics:

下载示例Download sample

下面的代码示例包含本教程中创建的代码:示例The following code sample contains the code that you created in this tutorial: sample.

后续步骤Next Steps

媒体服务 v3(最新版本)Media Services v3 (latest)

查看最新版本的 Azure 媒体服务!Check out the latest version of Azure Media Services!

媒体服务 v2(旧版)Media Services v2 (legacy)