首页 > 解决方案 > WPF MediaElement 播放方向

问题描述

我有一些 mp4(在 android 上捕获,一些是纵向的,一些是横向的)当我将它们用作 MediaElement 标签的来源时,它们总是以横向模式播放。我一直在疯狂地搜索这个,并没有找到任何关于 MediaElement 中视频方向的信息,所以希望我错过了一些基本的东西。

这是我的xml:

<Canvas x:Name="videoCanvas" Height="Auto" Width="641" Margin="10,0,11,0" HorizontalAlignment="Center" >
    <ContentControl Content="{Binding Media}" Width="{Binding ActualWidth, ElementName=videoCanvas}"  Height="{Binding ActualHeight, ElementName=videoCanvas}" />
</Canvas>

和代码隐藏:

  media = new MediaElement();
  media.LoadedBehavior = MediaState.Manual;            
  media.Loaded += Media_Loaded;
  media.MediaOpened += Media_MediaOpened;
  media.Source = new Uri(@"c:\videos\portrait.mp4");
  media.HorizontalAlignment = HorizontalAlignment.Center;
  media.VerticalAlignment = VerticalAlignment.Center;

Media_MediaOpened 中的 NaturalVideoHeight/Width 对于两个视频都是相同的,所以我认为我不能使用它来旋转 MediaElement。

标签: wpfmp4mediaelement

解决方案


在我的案例中,有一种方法可以解决这个问题。您需要使用 nugget Microsoft-WindowsAPICodePack-Core 和 Microsoft-WindowsAPICodePack-Shell:

ShellFile shell = ShellFile.FromFilePath(this.VideoFile);
ShellProperty<ulong?> fs = shell.Properties.System.Size;

// workaround to find out if video in portrait or landscape
BitmapSource bs = shell.Thumbnail.BitmapSource;
double bsWidth = bs.Width;
double bsHeight = bs.Height;
videoOrientation = bsWidth > bsHeight ? VideoOrientation.LANDSCAPE : VideoOrientation.PORTRAIT;

ShellProperty<uint?> fw = shell.Properties.System.Video.FrameWidth;
ShellProperty<uint?> fh = shell.Properties.System.Video.FrameHeight;

从代码中,我们看到视频具有缩略图表示,它是您在 Windows 资源管理器中浏览视频时看到的图像。使用“fw”和“fh”,您可以设置 aspectRatio 并正确设置属性 Width 和 Height od MediaElement。

希望它可以帮助某人。


推荐阅读