WinUI 3 MediaPlayerElement控件的一些操作
MediaPlayerElement控件UWP和WinUI 3均可使用,本文使用UWP演示
制作一个简易的MediaPlayer
添加MediaPlayerElement
MediaPlayerElement:
<MediaPlayerElement
x:Name="mediaPlayerElement"
Width="800"
AutoPlay="False"
AreTransportControlsEnabled="True"
/>
效果:
全屏模式下:
添加源视频文件
使用CommandBar控件
xaml
<StackPanel>
<CommandBar Background="Transparent" IsOpen="False" DefaultLabelPosition="Right">
<CommandBar.SecondaryCommands>
<AppBarButton Name="Mybtn" Icon="Setting" Label="Settings" Click="Mybtn_Click">
<AppBarButton.KeyboardAccelerators>
<KeyboardAccelerator Modifiers="Control" Key="I" />
</AppBarButton.KeyboardAccelerators>
</AppBarButton>
<AppBarButton Icon="Home" Label="Home">
<AppBarButton.KeyboardAccelerators>
<KeyboardAccelerator Modifiers="Control" Key="I" />
</AppBarButton.KeyboardAccelerators>
</AppBarButton>
</CommandBar.SecondaryCommands>
</CommandBar>
</StackPanel>
C#
WinUI 3版
private async void OpenFile_Click(object sender, RoutedEventArgs e)
{
await SetLocalMedia();
}
async private System.Threading.Tasks.Task SetLocalMedia()
{
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
WinRT.Interop.InitializeWithWindow.Initialize(openPicker, WinRT.Interop.WindowNative.GetWindowHandle(this));
openPicker.FileTypeFilter.Add(".wmv");
openPicker.FileTypeFilter.Add(".mp4");
openPicker.FileTypeFilter.Add(".wma");
openPicker.FileTypeFilter.Add(".mp3");
var file = await openPicker.PickSingleFileAsync();
// mediaPlayerElement is a MediaPlayerElement control defined in XAML
if (file != null)
{
mediaPlayerElement.Source = MediaSource.CreateFromStorageFile(file);
mediaPlayerElement.MediaPlayer.Play();
}
}
效果:
UWP版
private async void OpenFile_Click(object sender, RoutedEventArgs e)
{
await SetLocalMedia();
}
async private System.Threading.Tasks.Task SetLocalMedia()
{
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".wmv");
openPicker.FileTypeFilter.Add(".mp4");
openPicker.FileTypeFilter.Add(".wma");
openPicker.FileTypeFilter.Add(".mp3");
var file = await openPicker.PickSingleFileAsync();
// mediaPlayerElement is a MediaPlayerElement control defined in XAML
if (file != null)
{
mediaPlayerElement.Source = MediaSource.CreateFromStorageFile(file);
mediaPlayerElement.MediaPlayer.Play();
}
}
效果:
效果:
添加事件处理程序
最终效果:
源文件下载
本文参考:
使用选取器打开文件和文件夹 - UWP applications | Microsoft Learn
XAML 样式 - Windows apps | Microsoft Learn
创建自定义媒体传输控件 - Windows apps | Microsoft Learn