如何对自定义转换进行编码 - .NETHow to encode with a custom transform - .NET

媒体服务徽标 v3media services logo v3


使用 Azure 媒体服务进行编码时,可以根据流式传输文件教程中演示的行业最佳做法,使用推荐的内置预设之一快速入门。When encoding with Azure Media Services, you can get started quickly with one of the recommended built-in presets based on industry best practices as demonstrated in the Streaming files tutorial. 也可以构建自定义预设以针对特定方案或设备要求。You can also build a custom preset to target your specific scenario or device requirements.

注意事项Considerations

创建自定义预设时,请注意以下事项:When creating custom presets, the following considerations apply:

  • AVC 内容上的所有高度和宽度值必须是 4 的倍数。All values for height and width on AVC content must be a multiple of 4.
  • 在 Azure 媒体服务 v3 中,所有编码比特率均以每秒比特数为单位。In Azure Media Services v3, all of the encoding bitrates are in bits per second. 这与我们的 v2 API 的预设不同,后者使用 千比特/秒作为单位。This is different from the presets with our v2 APIs, which used kilobits/second as the unit. 例如,如果 v2 中的比特率指定为 128(千比特/秒),则在 v3 中它将设置为 128000(比特/秒)。For example, if the bitrate in v2 was specified as 128 (kilobits/second), in v3 it would be set to 128000 (bits/second).

先决条件Prerequisites

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

下载示例Download the sample

使用以下命令将包含完整 .NET Core 示例的 GitHub 存储库克隆到计算机:Clone a GitHub repository that contains the full .NET Core sample to your machine using the following command:

git clone https://github.com/Azure-Samples/media-services-v3-dotnet-core-tutorials.git

自定义预设示例位于 EncodeCustomTransform 文件夹中。The custom preset sample is located in the EncodeCustomTransform folder.

使用自定义预设创建转换Create a transform with a custom preset

创建新的转换时,需要指定希望生成的输出内容。When creating a new Transform, you need to specify what you want it to produce as an output. 所需参数是 TransformOutput 对象,如以下代码所示。The required parameter is a TransformOutput object, as shown in the code below. 每个 TransformOutput 包含一个预设 。Each TransformOutput contains a Preset. 预设介绍了视频和/或音频处理操作的分步说明,这些操作将用于生成所需的 TransformOutputThe Preset describes the step-by-step instructions of video and/or audio processing operations that are to be used to generate the desired TransformOutput. 以下 TransformOutput 创建自定义编解码器和层输出设置。The following TransformOutput creates custom codec and layer output settings.

在创建时转换,首先应检查是否其中一个已存在使用获取方法,如下面的代码中所示。When creating a Transform, you should first check if one already exists using the Get method, as shown in the code that follows. 在媒体服务 v3 中,如果实体不存在(对名称进行不区分大小写检查),实体上的 Get 方法将返回 nullIn Media Services v3, Get methods on entities return null if the entity doesn't exist (a case-insensitive check on the name).

示例Example

下面的示例定义了一组我们希望在使用此转换时生成的输出。The following example defines a set of outputs that we want to be generated when this Transform is used. 我们首先为音频编码添加一个 AacAudio 层,为视频编码添加两个 H264Video 层。We first add an AacAudio layer for the audio encoding and two H264Video layers for the video encoding. 在视频层中,我们分配标签,以便可以在输出文件名中使用它们。In the video layers, we assign labels so that they can be used in the output file names. 接下来,我们希望输出还包括缩略图。Next, we want the output to also include thumbnails. 在以下示例中,我们指定 PNG 格式的图像,这些图像以输入视频分辨率的 50% 生成,并以输入视频长度的 {25%, 50%, 75%} 三个时间戳生成。In the example below we specify images in PNG format, generated at 50% of the resolution of the input video, and at three timestamps - {25%, 50%, 75%} of the length of the input video. 最后,我们指定输出文件的格式 - 一个用于视频 + 音频,另一个用于缩略图。Lastly, we specify the format for the output files - one for video + audio, and another for the thumbnails. 由于我们有多个 H264 层,因此我们必须使用宏来为每个层生成唯一的名称。Since we have multiple H264Layers, we have to use macros that produce unique names per layer. 可以使用 {Label}{Bitrate} 宏,此示例显示了前者。We can either use a {Label} or {Bitrate} macro, the example shows the former.

private static Transform EnsureTransformExists(IAzureMediaServicesClient client, string resourceGroupName, string accountName, string transformName)
{
    // Does a Transform already exist with the desired name? Assume that an existing Transform with the desired name
    // also uses the same recipe or Preset for processing content.
    Transform transform = client.Transforms.Get(resourceGroupName, accountName, transformName);

    if (transform == null)
    {
        // Create a new Transform Outputs array - this defines the set of outputs for the Transform
        TransformOutput[] outputs = new TransformOutput[]
        {
            // Create a new TransformOutput with a custom Standard Encoder Preset
            // This demonstrates how to create custom codec and layer output settings

          new TransformOutput(
                new StandardEncoderPreset(
                    codecs: new Codec[]
                    {
                        // Add an AAC Audio layer for the audio encoding
                        new AacAudio(
                            channels: 2,
                            samplingRate: 48000,
                            bitrate: 128000,
                            profile: AacAudioProfile.AacLc
                        ),
                        // Next, add a H264Video for the video encoding
                       new H264Video (
                            // Set the GOP interval to 2 seconds for both H264Layers
                            keyFrameInterval:TimeSpan.FromSeconds(2),
                             // Add H264Layers, one at HD and the other at SD. Assign a label that you can use for the output filename
                            layers:  new H264Layer[]
                            {
                                new H264Layer (
                                    bitrate: 1000000, // Units are in bits per second
                                    width: "1280",
                                    height: "720",
                                    label: "HD" // This label is used to modify the file name in the output formats
                                ),
                                new H264Layer (
                                    bitrate: 600000, 
                                    width: "640",
                                    height: "360",
                                    label: "SD"
                                )
                            }
                        ),
                        // Also generate a set of PNG thumbnails
                        new PngImage(
                            start: "25%",
                            step: "25%",
                            range: "80%",
                            layers: new PngLayer[]{
                                new PngLayer(
                                    width: "50%", 
                                    height: "50%"
                                )
                            }
                        )
                    },
                    // Specify the format for the output files - one for video+audio, and another for the thumbnails
                    formats: new Format[]
                    {
                        // Mux the H.264 video and AAC audio into MP4 files, using basename, label, bitrate and extension macros
                        // Note that since you have multiple H264Layers defined above, you have to use a macro that produces unique names per H264Layer
                        // Either {Label} or {Bitrate} should suffice
                         
                        new Mp4Format(
                            filenamePattern:"Video-{Basename}-{Label}-{Bitrate}{Extension}"
                        ),
                        new PngFormat(
                            filenamePattern:"Thumbnail-{Basename}-{Index}{Extension}"
                        )
                    }
                ),
                onError: OnErrorType.StopProcessingJob,
                relativePriority: Priority.Normal
            )
        };

        string description = "A simple custom encoding transform with 2 MP4 bitrates";
        // Create the custom Transform with the outputs defined above
        transform = client.Transforms.CreateOrUpdate(resourceGroupName, accountName, transformName, outputs, description);
    }

    return transform;
}

后续步骤Next steps

流式传输文件Streaming files