WPF利用MediaElement编写视频播放器
1、打开VS,选择Visual C#模板创建WPF应用程序。输入一个自己满意的解决方案名称,并指定其位置,点击确认按钮进入代码编写界面。
2、在MainWindow.xaml页面中添加如下代码:<Window x:Class="稆糨孝汶;MyMedia.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="我的播放器-拖动文件执行" Height="350" Width="525"> <Grid> <MediaElement Name="mediaElement1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Stretch="Fill" IsMuted="False" /> <Grid x:Name="GridDrag" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" AllowDrop="True" DragEnter="G_DragEnter" DragOver="G_DragOver" Background="#02000000" /> </Grid></Window>
3、在MainWindow.xaml.cs页面中添加如下代码:using System挢旗扦渌;using System.Colle艘早祓胂ctions.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace MyMedia{ /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.mediaElement1.LoadedBehavior = MediaState.Manual; } private void G_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effects = DragDropEffects.All; else e.Effects = DragDropEffects.None; } private void G_DragOver(object sender, DragEventArgs e) { string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false); this.mediaElement1.Source = new Uri(s[0]); mediaElement1.Play(); mediaElement1.Volume = 1; } }}
4、编译代码,生成解决方案。
5、编译成功后,按F5执行,拖动一个可以播放的视频文件放置到软件窗口中,视频将开始自动播放。
6、以上5个步骤就实现一个播放器最基本的播放功能。但视频一般还会有暂停、快进、全屏等功能。为此,我们可能需要做不少UI等润色工作,让我们的播放器漂亮起来。