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 <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.Collections.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等润色工作,让我们的播放器漂亮起来。
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:125
阅读量:80
阅读量:23
阅读量:116
阅读量:186