查询设备上安装的编解码器

通过 CodecQuery 类可以查询安装在当前设备上的编解码器。 文章支持的编解码器中给出了 Windows 10 附带的用于不同设备系列的编解码器列表,但是由于用户和应用可以在设备上安装其他编解码器,因此你可能要在运行时查询编解码器支持,以确定当前设备上可用的编解码器。

CodecQuery API 是 Windows.Media.Core 命名空间的成员,因此需要在应用中包含此命名空间。

using Windows.Media.Core;

通过调用构造函数来初始化 CodecQuery 类的新实例。

var codecQuery = new CodecQuery();

FindAllAsync 方法返回与提供的参数匹配的所有已安装编解码器。 这些参数包括用于指定查询音频编解码器和/或视频编解码器的 CodecKind 值、用于指定查询编码器或解码器的 CodecCategory 值以及表示所查询的媒体编码子类型(如 H.264 视频或 MP3 音频)的字符串。

为子类型值指定空字符串以返回适用于所有子类型的编解码器。 以下示例列出了设备上安装的所有视频编码器。

IReadOnlyList<CodecInfo> result =
    await codecQuery.FindAllAsync(CodecKind.Video, CodecCategory.Encoder, "");

foreach (var codecInfo in result)
{
    this.codecResultsTextBox.Text += "============================================================\n";
    this.codecResultsTextBox.Text += string.Format("Codec: {0}\n", codecInfo.DisplayName);
    this.codecResultsTextBox.Text += string.Format("Kind: {0}\n", codecInfo.Kind.ToString());
    this.codecResultsTextBox.Text += string.Format("Category: {0}\n", codecInfo.Category.ToString());
    this.codecResultsTextBox.Text += string.Format("Trusted: {0}\n", codecInfo.IsTrusted.ToString());

    foreach (string subType in codecInfo.Subtypes)
    {
        this.codecResultsTextBox.Text += string.Format("   Subtype: {0}\n", subType);
    }
}

传入到 FindAllAsync 的子类型字符串可以是系统定义的子类型 GUID 的字符串表示形式或子类型的 FOURCC 代码。 音频子类型 GUID视频子类型 GUID 文章中列出了支持的媒体子类型 GUID 集,但是 CodecSubtypes 类提供了返回每个受支持子类型的 GUID 值的属性。 有关 FOURCC 代码的详细信息,请参阅 FOURCC 代码

以下示例指定 FOURCC 代码“H264”,以确定是否在设备上安装了 H.264 视频解码器。 可以在尝试播放 H.264 视频内容之前执行此查询。 还可以在播放时处理不支持的编解码器。 有关详细信息,请参阅在打开媒体项时,处理不受支持的编解码器和未知错误

IReadOnlyList<CodecInfo> h264Result = await codecQuery.FindAllAsync(CodecKind.Video, CodecCategory.Decoder, "H264");

if (h264Result.Count > 0)
{
    this.codecResultsTextBox.Text = "H264 decoder is present.";
}

以下示例中,进行查询的目的是确定当前设备上是否已安装 FLAC 音频编码器。如果已安装,则为子类型创建 MediaEncodingProfile,它可用于将音频捕获到文件中或是将音频从另一种格式转码为 FLAC 音频文件。

IReadOnlyList<CodecInfo> flacResult = 
    await codecQuery.FindAllAsync(CodecKind.Audio, CodecCategory.Encoder, CodecSubtypes.AudioFormatFlac);

if (flacResult.Count > 0)
{
    AudioEncodingProperties audioProps = new AudioEncodingProperties();
    audioProps.Subtype = CodecSubtypes.AudioFormatFlac;
    audioProps.SampleRate = 44100;
    audioProps.ChannelCount = 2;
    audioProps.Bitrate = 128000;
    audioProps.BitsPerSample = 32;

    MediaEncodingProfile encodingProfile = new MediaEncodingProfile();
    encodingProfile.Audio = audioProps;
    encodingProfile.Video = null;
}