UWP:使用MediaPlayerElement实现媒体播放器
2017-04-21 14:43
225 查看
1.代码部分
UI界面(Mainpage.XAML):<Page x:Class="Homework8.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:Homework8" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:c="using:Homework8.Converter" mc:Ignorable="d"> <Page.Resources> <c:timeLineConverter x:Key="converter" /> <Storyboard x:Name="EllStoryboard" RepeatBehavior="Forever"> <DoubleAnimation Duration="0:0:20" To="360" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.Rotation)" Storyboard.TargetName="Picture" d:IsOptimized="True"/> </Storyboard> </Page.Resources> <Page.BottomAppBar> <CommandBar> <AppBarButton Name="start" Icon="Play" FontSize="20" Click="start_Click" HorizontalAlignment="Left" Label="播放"/> <AppBarButton Name="pause" Icon="Pause" FontSize="20" Click="pause_Click" Label="暂停"/> <AppBarButton Name="stop" Icon="Stop" FontSize="20" Click="stop_Click" Label="停止"/> <AppBarButton Name="add" Icon="OpenFile" FontSize="20" Click="add_Click" Label="选择文件"/> <AppBarButton Name="display" Icon="FullScreen" FontSize="20" Click="display_Click" Label="全屏"/> </CommandBar> </Page.BottomAppBar> <Grid Name="MyGrid"> <Grid.Background> <ImageBrush ImageSource="Assets/3.jpg" Opacity="0.5" /> </Grid.Background> <Grid.RowDefinitions> <RowDefinition Height="auto" /> <RowDefinition Height="*" /> <RowDefinition Height="auto" /> </Grid.RowDefinitions> <TextBlock Name="Title" Text="MediaPlayer" Margin="25" Style="{StaticResource HeaderTextBlockStyle}" FontWeight="Bold" HorizontalAlignment="Center" /> <Ellipse Width="450" Height="450" Margin="75,45,75,45" Grid.Row="1" Name="Picture" Visibility="Collapsed" VerticalAlignment="Center" HorizontalAlignment="Center" RenderTransformOrigin="0.5, 0.5"> <Ellipse.RenderTransform> <CompositeTransform /> </Ellipse.RenderTransform> <Ellipse.Fill> <ImageBrush ImageSource="Assets/2.jpg"/> </Ellipse.Fill> </Ellipse> <MediaPlayerElement x:Name="_mediaPlayerElement" AreTransportControlsEnabled="False" HorizontalAlignment="Stretch" Grid.Row="1"/> <StackPanel Grid.Row="2"> <Slider Padding="50,0,50,0" x:Name="timeLine" Value="{x:Bind _mediaTimelineController.Position, Converter={StaticResource converter},Mode=TwoWay}"/> <StackPanel Orientation="Horizontal"> <AppBarButton Icon="Volume" IsCompact="True" VerticalAlignment="center" Margin="30,0,0,0"/> <Slider Minimum="0" Maximum="1" Name="Volumn" Width="70" Value="0.5" StepFrequency="0.1" ValueChanged="Volumn_ValueChanged" /> </StackPanel> </StackPanel> </Grid> </Page>
后台实现(Mainpage.xaml.cs):
using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; //“空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 上有介绍 namespace Homework8 { /// <summary> /// 可用于自身或导航至 Frame 内部的空白页。 /// </summary> public sealed partial class MainPage : Page { MediaPlayer _mediaPlayer = new MediaPlayer(); MediaTimelineController _mediaTimelineController = new MediaTimelineController(); TimeSpan _duration; // MediaPlaybackSession _mediaPlaybackSession = new MediaPlaybackSession(); public MainPage() { this.InitializeComponent(); var mediaSource = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/Video1.MP4")); mediaSource.OpenOperationCompleted += MediaSource_OpenOperationCompleted; _mediaPlayer.Source = mediaSource; _mediaPlayer.CommandManager.IsEnabled = false; _mediaPlayer.TimelineController = _mediaTimelineController; //_mediaPlayer.Play(); _mediaPlayerElement.SetMediaPlayer(_mediaPlayer); } private void pause_Click(object sender, RoutedEventArgs e) { try { if (_mediaTimelineController.State == MediaTimelineControllerState.Running) { EllStoryboard.Pause(); _mediaTimelineController.Pause(); } else { //EllStoryboard.Resume(); EllStoryboard.Begin(); _mediaTimelineController.Resume(); } } catch { } } private void start_Click(object sender, RoutedEventArgs e) { try { DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(1); timer.Tick += timer_Tick; timer.Start(); EllStoryboard.Begin(); _mediaTimelineController.Start(); } catch { } } void timer_Tick(object sender, object e) { timeLine.Value = ((TimeSpan)_mediaTimelineController.Position).TotalSeconds; if (timeLine.Value == timeLine.Maximum) { _mediaTimelineController.Position = TimeSpan.FromSeconds(0); _mediaTimelineController.Pause(); EllStoryboard.Stop(); } } private void stop_Click(object sender, RoutedEventArgs e) { try { _mediaTimelineController.Position = TimeSpan.FromSeconds(0); _mediaTimelineController.Pause(); EllStoryboard.Stop(); } catch { } } private void display_Click(object sender, RoutedEventArgs e) { ApplicationView view = ApplicationView.GetForCurrentView(); bool isInFullScreenMode = view.IsFullScreenMode; if (isInFullScreenMode) { ImageBrush imageBrush = new ImageBrush(); imageBrush.ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/3.jpg", UriKind.Absolute)); MyGrid.Background = imageBrush; MyGrid.Background.Opacity = 0.5; view.ExitFullScreenMode(); } else { MyGrid.Background = new SolidColorBrush(Colors.Black);// Windows.UI.Xaml.Media.Brush view.TryEnterFullScreenMode(); } } private async void add_Click(object sender, RoutedEventArgs e) { var openPicker = new FileOpenPicker(); openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary; openPicker.FileTypeFilter.Add(".wmv"); openPicker.FileTypeFilter.Add(".mp4"); openPicker.FileTypeFilter.Add(".mp3"); openPicker.FileTypeFilter.Add(".wma"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { var mediaSource = MediaSource.CreateFromStorageFile(file); mediaSource.OpenOperationCompleted += MediaSource_OpenOperationCompleted; _mediaPlayer.Source = mediaSource; if (file.FileType == ".mp3" || file.FileType == ".wma") { Picture.Visibility = Visibility.Visible; //_mediaPlayerElement.Visibility = Visibility.Collapsed; } else { Picture.Visibility = Visibility.Collapsed; //_mediaPlayerElement.Visibility = Visibility.Visible; } } } private void Volumn_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) { _mediaPlayer.Volume = (double)Volumn.Value; } private async void MediaSource_OpenOperationCompleted(MediaSource sender, MediaSourceOpenOperationCompletedEventArgs args) { _duration = sender.Duration.GetValueOrDefault(); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { timeLine.Minimum = 0; timeLine.Maximum = _duration.TotalSeconds; timeLine.StepFrequency = 1; }); } } }
转换器(用于将视频进度条的Position转化成Slider的Value):
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Data; namespace Homework8.Converter { class timeLineConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { return ((TimeSpan)value).TotalSeconds; } public object ConvertBack(object value, Type targetType, object parameter, string language) { return TimeSpan.FromSeconds((double)value); } } }
使用说明:
代码仅供参考,如要编译运行,请把项目的名称定义为Homework8;
添加自己的视频到Assets目录,修改代码中初始化的视频文件;
在项目中新建一个Converter文件夹,在文件夹中添加一个类,用于定义上面提到的转化器。
效果图如下:
(1)本地选取视频
(2)播放视频
(3)全屏效果
(4)退出全屏
(5)选取音乐
(6)播放音乐
2.实现过程(截图来自我的实验报告)
由于详细的实现过程在实验报告里写的很清楚了,所以我就直接截图过来了~以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!
相关文章推荐
- Android中使用SurfaceView+MediaPlayer+自定义的MediaController实现自定义的视屏播放器
- android使用MediaPlayer+Surface实现简单视频播放器
- Visual Studio 2010 使用Windows Media Player控件实现播放音乐视频
- Android视频播放框架Vitamio集成及使用MediaPlayer+SurfaceView、VideoView+MediaController实现播放网络视频
- 使用SurfaceView+MediaPlayer+SeekBar实现视屏播放器
- 使用SurfaceView+MediaPlayer+SeekBar实现视频播放
- NaiveMediaPlayer——UWP简单的播放器实现(for MP3/MP4)
- (8): 使用 TMediaPlayer 录制 wav 文件
- AxWindowsMediaPlayer控件的使用方法
- Windows Media Player界面的实现
- 在Silverlight中使用SmoothStreamingMediaElement创建Smooth Streaming播放器
- 网页实现歌曲连播(Js+MediaPlayer)
- Windows Media Player控件的使用和使用心得
- AxWindowsMediaPlayer控件的使用方法
- VC2008 Windows Media Player控件的使用技巧(三)
- jw flv media player 的使用问题
- VS2003下windows media player 控件的使用问题
- 使用P/Invoke、C#与Windows Media Player互操作(一)
- Windows Mobile和Wince下使用WTL进行Windows Media Player开发
- VS2003下windows media player 控件的使用問題(轉載)