一个很小很小的 Music、Video 播放器,有效代码不足 20 行,却能够 Play、Pause、Stop 和调整播放位置。
其界面代码如下:
MediaWindow.xaml
<Window x:Class="x01.WpfTest.MediaWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Media Player by x01" WindowStartupLocation="CenterScreen" Width="650" Height="450" > <DockPanel> <DockPanel.Background> <RadialGradientBrush> <GradientStop Color="#FFD7EEEC" Offset="0"/> <GradientStop Color="#FF89AAA7" Offset="1"/> <GradientStop Color="#FF5A8984" Offset="0.365"/> <GradientStop Color="#FFA9E6DF" Offset="0.585"/> <GradientStop Color="#FF16897F" Offset="0.798"/> </RadialGradientBrush> </DockPanel.Background> <StackPanel DockPanel.Dock="Bottom" Height="60" Orientation="Horizontal" HorizontalAlignment="Center"> <Image Name="imgPlay" Source="Resources/play.png" ToolTip="Play" Margin="5" /> <Image Name="imgPause" Source="Resources/pause.png" ToolTip="Pause" Margin="5" /> <Image Name="imgStop" Source="Resources/stop.png" ToolTip="Stop" Margin="5" /> <Slider Name="sliderPos" Width="250" VerticalAlignment="Center" Margin="5" /> <Button Name="btnSelect" Content="_Select" ToolTip="Select Music(mp3) or Video(mp4)" Width="100" Margin="10" FontSize="16" /> </StackPanel> <MediaElement x:Name="media" LoadedBehavior="Manual" Margin="0 2 0 0" UnloadedBehavior="Stop" /> </DockPanel> </Window>
主代码如下:
MediaWindow.xaml.cs
public partial class MediaWindow : Window { OpenFileDialog _dlgOpen = new OpenFileDialog(); public MediaWindow() { InitializeComponent(); _dlgOpen.Filter = "MP4(*.mp4)|*.mp4|WMV(*.wmv)|*.wmv|MP3(*.mp3)|*.mp3|All File(*.*)|*.*"; media.MediaOpened += (s, e) => sliderPos.Maximum = media.NaturalDuration.TimeSpan.TotalMilliseconds; media.MediaEnded += (s, e) => media.Stop(); sliderPos.ValueChanged += (s, e) => { media.Position = new TimeSpan(0, 0, 0, 0, (int)sliderPos.Value); if (sliderPos.Value < sliderPos.Maximum && sliderPos.Value != 0) { media.Play(); } }; imgPlay.MouseDown += (s, e) => media.Play(); imgPause.MouseDown += (s, e) => media.Pause(); imgStop.MouseDown += (s, e) => { media.Stop(); sliderPos.Value = 0; }; btnSelect.Click += (s, e) => { bool ok = (bool)_dlgOpen.ShowDialog(); if (ok) { string file = _dlgOpen.FileName; this.Title = file.Substring(file.LastIndexOf('\\') + 1); media.Source = new Uri(file); media.Play(); } }; } }
当然,通过 Reflector 反编译,也是一个不错的选择。其程序 MediaPlayer.exe 放在 x01.Download 中。
需要说明的是,MediaElement 的 LoadedBehavior="Manual" 方可。