WPF利用MediaElement编写视频播放器

2025-06-16 06:14:11

1、打开VS,选择Visual C#模板创建WPF应用程序。输入一个自己满意的解决方案名称,并指定其位置,点击确认按钮进入代码编写界面。

WPF利用MediaElement编写视频播放器

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; } }}

WPF利用MediaElement编写视频播放器

5、编译成功后,按F5执行,拖动一个可以播放的视频文件放置到软件窗口中,视频将开始自动播放。

WPF利用MediaElement编写视频播放器

6、以上5个步骤就实现一个播放器最基本的播放功能。但视频一般还会有暂停、快进、全屏等功能。为此,我们可能需要做不少UI等润色工作,让我们的播放器漂亮起来。

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢