MVVM模式基于开源VLC解码器WPF万能视频播放器

采用VLC解码器,能播放市面上几乎所有格式影片。

MVVM模式基于开源VLC解码器WPF万能视频播放器_第1张图片

Models:SysInfo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MvvmPlayer.Models
{
    public  class SysInfo
    {
        public  string Title { get; set; }   //标题

        public string MediaFile { get; set; }   //媒体文件

        public float MediaPosition { get; set; }    //播放进度

        public string MediaTime { get; set; }  //播放时间

        //public double MediaVolume { get; set; }     //音量

        //public bool IsMute { get; set; }  //是否静音
    }
}

ViewModels:VideoPlayerViewModel

using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Vlc.DotNet.Core;
using Vlc.DotNet.Wpf;
using MvvmPlayer.Models;
using System.Windows.Media;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using Microsoft.Win32;
using Vlc.DotNet.Core.Medias;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace MvvmPlayer.ViewModels
{
    public class VideoPlayerViewModel : ViewModelBase
    {

        #region 构造方法

        public VideoPlayerViewModel()
        {
            if (!VlcContext.IsInitialized)
                InitEncoder();
            _sysInfo = new SysInfo();
            myVideo = new VlcControl();          
	    this.Title = "作者:腾飞大侠 邮箱:[email protected]";
            this.MediaTime = "作者:腾飞大侠 邮箱:[email protected]";
this.PlayerWindowStyle = WindowStyle.ThreeDBorderWindow; this.PlayerWindowState = WindowState.Normal; this.GridVideoScaleY = 1; this.MyVideo.TimeChanged += myVideo_TimeChanged; //定义视频播放时间改变事件 this.MyVideo.PositionChanged += myVideo_PositionChanged; //定义播放位置改变事件 } #endregion #region 初始化事件 // 播放控件拖放事件 void gridVideo_Drop(object sender, DragEventArgs e) { //获取拖拽的文件 string fileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString(); this.MyVideo.Stop(); this.MyVideo.Media = new PathMedia(fileName); System.Threading.Thread.Sleep(1); this.MyVideo.Play(); } //播放控件拖放事件 void gridVideo_DragEnter(object sender, DragEventArgs e) { //仅支持文件的拖放 if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effects = DragDropEffects.Link; else e.Effects = DragDropEffects.None; } // 窗口关闭事件 private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { VlcContext.CloseAll(); //关闭解码器环境 } // 播放位置改变事件 private void myVideo_PositionChanged(VlcControl sender, VlcEventArgs e) { if (myPositionChanging) //如果正在拖动进度条,则暂时不改变进度条的值 return; this.MediaPosition = e.Data; //改变进度条的值 } #region 进度条处理事件 // 进度条拖动事件 private bool myPositionChanging; private void sliderPosition_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { myPositionChanging = true; //位置改变设置为true this.MediaPosition = (float)sliderPosition.Value; //媒体进度值等于进度条的值 this.MyVideo.PositionChanged -= myVideo_PositionChanged; //删除播放位置改变事件 } // 完成拖播放进度条 private void sliderPosition_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { this.MyVideo.Position = (float)sliderPosition.Value; //设置播放进度,等于进度条的值 this.MyVideo.PositionChanged += myVideo_PositionChanged; //添加播放位置改变事件 myPositionChanging = false; } // 进度条值改变 void sliderPosition_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) { this.MediaPosition = (float)e.NewValue; //设置播放位置 } #endregion // 鼠标移动时,显示播放进度条 DispatcherTimer timer1 = null; void gridVideo_MouseMove(object sender, MouseEventArgs e) { if (timer1 == null) { timer1 = new DispatcherTimer(); } if (this.PlayerWindowState == WindowState.Maximized) //判断窗口是否为最大化 { SliderPositionVisibility = Visibility.Visible; //显示播放进度条 Mouse.OverrideCursor = null; //恢复鼠标显示 timer1.Interval = TimeSpan.FromSeconds(4); //鼠标4秒不动,自动隐藏 timer1.Tick += (s, e1) => { SliderPositionVisibility = Visibility.Hidden; //隐藏播放进度条 Mouse.OverrideCursor = Cursors.None; //隐藏鼠标 timer1.IsEnabled=false; //禁用计时器 }; timer1.IsEnabled=true; } else if(this.playerWindowState==WindowState.Normal) { timer1.IsEnabled=false; SliderPositionVisibility = Visibility.Visible; //显示进度条 Mouse.OverrideCursor = null; //恢复鼠标显示 } } // 播放时间改变 private void myVideo_TimeChanged(VlcControl sender, VlcEventArgs e) { var duration = this.MyVideo.Media == null ? TimeSpan.Zero : this.MyVideo.Media.Duration; var time = TimeSpan.FromMilliseconds(duration.TotalMilliseconds * this.MediaPosition); //显示播放时间 this.MediaTime = string.Format("时间:" + "{0:00}:{1:00}:{2:00}/{3:00}:{4:00}:{5:00}", time.Hours, time.Minutes, time.Seconds, duration.Hours, duration.Minutes, duration.Seconds ); //设置媒体时间属性 } //private void Media_ParsedChanged(MediaBase sender, VlcEventArgs e) //{ // this.MediaTime = string.Format( // "时间:{0:00}:{1:00}:{2:00}", // this.MyVideo.Media.Duration.Hours, // this.MyVideo.Media.Duration.Minutes, // this.MyVideo.Media.Duration.Seconds // ); // this.MediaVolume = myVideo.AudioProperties.Volume; //} #endregion #region 初始化属性 private double gridVideoScaleY; public double GridVideoScaleY //视频翻转 { get { return gridVideoScaleY; } set { gridVideoScaleY = value; RaisePropertyChanged("GridVideoScaleY"); } } private bool playerTopmost; public bool PlayerTopmost //窗口置顶 { get { return playerTopmost; } set { playerTopmost = value; RaisePropertyChanged("PlayerTopmost"); } } private WindowStyle playerWindowStyle; public WindowStyle PlayerWindowStyle //窗口样式 { get { return playerWindowStyle; } set { playerWindowStyle = value; RaisePropertyChanged("PlayerWindowStyle"); } } private Visibility sliderPositionVisibility; public Visibility SliderPositionVisibility //进度条状态 { get { return sliderPositionVisibility; } set { sliderPositionVisibility = value; RaisePropertyChanged("SliderPositionVisibility"); } } private Visibility ctrolPanelVisibility; public Visibility CtrolPanelVisibility //控制面板状态 { get { return ctrolPanelVisibility; } set { ctrolPanelVisibility = value; RaisePropertyChanged("CtrolPanelVisibility"); } } private WindowState playerWindowState; public WindowState PlayerWindowState //器窗口状态 { get { return playerWindowState; } set { if (playerWindowState != value) { playerWindowState = value; RaisePropertyChanged("PlayerWindowState"); } } } private VlcControl myVideo; public VlcControl MyVideo //定义VlcControl控件 { get { return myVideo; } } private SysInfo _sysInfo; public SysInfo SysInfo //系统信息 { get { return _sysInfo; } set { _sysInfo = value; } } public string Title //标题 { get { return SysInfo.Title; } set { SysInfo.Title = value; RaisePropertyChanged("Title"); } } public string MediaFile //媒体文件 { get { return SysInfo.MediaFile; } set { SysInfo.MediaFile = value; RaisePropertyChanged("MediaFile"); } } public float MediaPosition //播放位置 { get { return SysInfo.MediaPosition; } set { if (SysInfo.MediaPosition != value) { SysInfo.MediaPosition = value; RaisePropertyChanged("MediaPosition"); } } } public int MediaVolume //音量 { get { return MyVideo.AudioProperties.Volume; } set { if (MyVideo.AudioProperties.Volume != value) { MyVideo.AudioProperties.Volume = value; RaisePropertyChanged("MediaVolume"); } } } public string MediaTime //播放时间 { get { return SysInfo.MediaTime; } set { SysInfo.MediaTime = value; RaisePropertyChanged("MediaTime"); } } #endregion #region 初始化命令 public ICommand WindowCommand //窗体命令 { get { return new RelayCommand((e) => { if (Application.Current.Properties["VideoPlayerArgName"] != null) //如果启动的时候带媒体参数 { string fname = Application.Current.Properties["VideoPlayerArgName"].ToString(); //ArbitraryArgName要与APP里面设置的名字相同 this.MyVideo.Media = new PathMedia(fname); MyVideo.Play(); } Window videoPlayer=e.OriginalSource as Window; videoPlayer.Closing += Window_Closing; }); } } public ICommand TxtgridVideoScaleTransformCommand //视频翻转 { get { return new RelayCommand((e) => { if (this.GridVideoScaleY == 1) { this.GridVideoScaleY = -1; } else if (this.GridVideoScaleY == -1) { this.GridVideoScaleY = 1; } }); } } Slider sliderPosition = null; public ICommand SliderPositionCommand //进度条初始化命令 { get { return new RelayCommand((e) => { sliderPosition = e.OriginalSource as Slider; sliderPosition.PreviewMouseLeftButtonDown += sliderPosition_MouseLeftButtonDown; sliderPosition.PreviewMouseLeftButtonUp += sliderPosition_MouseLeftButtonUp; sliderPosition.ValueChanged += sliderPosition_ValueChanged; }); } } int i = 0; Grid gridVideo = null; public ICommand GridVideoCommand //播放控件命令 { get { return new RelayCommand((e) => { gridVideo = e.OriginalSource as Grid; //获取事件触发源 gridVideo.MouseLeftButtonDown += gridVideo_MouseLeftButtonDown; gridVideo.DragEnter += gridVideo_DragEnter; gridVideo.Drop += gridVideo_Drop; }); } } /// /// 播放控件鼠标单击事件 /// /// /// void gridVideo_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { i++; DispatcherTimer timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 0, 0, 300); //双击间隔时间为300毫秒 timer.Tick += (s, e1) => { timer.IsEnabled = false; i = 0; }; timer.IsEnabled = true; if (i % 2 == 0) { timer.IsEnabled = false; i = 0; if (this.PlayerWindowState != WindowState.Maximized) //双击全屏 { gridVideo.MouseMove += gridVideo_MouseMove; //鼠标移动事件 this.PlayerWindowStyle = WindowStyle.None; //设置窗口样式 this.PlayerWindowState = WindowState.Maximized; //设置窗口大小 //如果想让开始菜单显示出来,跟上面正好相反 //this.WindowState = WindowState.Maximized; //this.WindowStyle = WindowStyle.None; this.CtrolPanelVisibility = Visibility.Collapsed; //隐藏控件 this.SliderPositionVisibility = Visibility.Collapsed; gridVideo.Margin = new Thickness(0, 0, 0, 0); //设置边界 //gridVideo.Width = SystemParameters.WorkArea.Width; this.PlayerTopmost = true; //窗口置顶 } else if (this.playerWindowState == WindowState.Maximized) //全屏状态下,双击恢复正常状态 { timer1.IsEnabled = false; //禁用timer1,否则从全屏切换到正常状态下,进度条会隐藏 gridVideo.MouseMove -= gridVideo_MouseMove; this.PlayerWindowState = WindowState.Normal; this.PlayerWindowStyle = WindowStyle.SingleBorderWindow; this.CtrolPanelVisibility = Visibility.Visible; this.SliderPositionVisibility = Visibility.Visible; gridVideo.Margin = new Thickness(0, 0, 0, 54); this.PlayerTopmost = false; Mouse.OverrideCursor = null; } } } public ICommand OpenMediaFile //打开 { get { return new RelayCommand(() => { this.MyVideo.Stop(); this.MediaPosition = 0; var ofd = new OpenFileDialog { FileName = "", Title = "打开媒体文件", Filter = "所有文件|*.*" }; //ofd.InitialDirectory = Environment.CurrentDirectory; ofd.RestoreDirectory = true; if (ofd.ShowDialog() != true || ofd.FileName == null) return; this.Title = System.IO.Path.GetFileName(ofd.FileName); this.MediaFile = ofd.FileName; this.MyVideo.Media = new PathMedia(this.MediaFile); //this.MyVideo.Media.ParsedChanged += Media_ParsedChanged; this.MyVideo.Play(); }); } } public ICommand PlayMedia //播放 { get { return new RelayCommand(() => { this.MyVideo.Play(); }); } } public ICommand PauseMedia //暂停 { get { return new RelayCommand(() => { this.MyVideo.Pause(); }); } } public ICommand StopMedia //停止 { get { return new RelayCommand(() => { this.MyVideo.Stop(); this.MediaPosition = 0; this.MediaTime = "作者:腾飞大侠 邮箱:[email protected]"; }); } } #endregion /// /// 初始化解码器 /// private void InitEncoder() { #region 初始化 // 设置解码器路径 //VlcContext.LibVlcDllsPath = System.IO.Path.Combine(Environment.CurrentDirectory, "libs"); VlcContext.LibVlcDllsPath = @"D:\VLC"; // 设置解码器插件路径 //VlcContext.LibVlcPluginsPath = System.IO.Path.Combine(Environment.CurrentDirectory, @"libs\plugins"); VlcContext.LibVlcPluginsPath = @"D:\VLC\plugins"; // 忽略解码器配置文件 VlcContext.StartupOptions.IgnoreConfig = true; // 是否记录日志文件 VlcContext.StartupOptions.LogOptions.LogInFile = false; // 显示解码器日志控件台 VlcContext.StartupOptions.LogOptions.ShowLoggerConsole = false; // 设置解码器记录日志级别 VlcContext.StartupOptions.LogOptions.Verbosity = VlcLogVerbosities.Debug; // 显示媒体文件名称 VlcContext.StartupOptions.AddOption("--no-video-title-show"); // 最后一个画面显示播放或暂停 //VlcContext.StartupOptions.AddOption("--play-and-pause"); // 初始化解码器 VlcContext.Initialize(); #endregion } }}
 
  Views:VideoPlayer.xaml 
  


    
        
    
    
	
    
	

        
        
		
			
				
                    
                     
					
				
						
			
				
					
						
					
				
			
			
                
                    
				
			
		
        
			
				
					
					
					
				
			
			
			
            
                
				
                    
				
			
            
            

App.xaml.cs:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace MvvmPlayer
{
    /// 
    /// App.xaml 的交互逻辑
    /// 
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args != null && e.Args.Count() > 0)   //如果参数不为空,且参数个数大于0
            {
                this.Properties["VideoPlayerArgName"] = e.Args[0];
            }  
            Views.VideoPlayer view = new Views.VideoPlayer();
            view.Show();
            base.OnStartup(e);
        }
    }
}


 
 

你可能感兴趣的:(WPF实例)