WPF视频播放器自做

合集下载

WPF MediElement实现视频播放

WPF MediElement实现视频播放

WPF MediElement实现视频播放WPF中可以使用MediaElement控件来进行音视频播放,然后需要做个进度条啥的,但是MediaElement.Position(进度)和MediaElement.NaturalDuration居然都不是依赖属性,简直不能忍!好吧,首先说说比较传统的做法(winform?)slider用来显示进度以及调整进度,tb1显示当前进度的时间值,tb2显示视频的时常。

player_Loaded 事件中使用DispatcherTimer来定时器获取当前视频的播放进度,player_MediaOpened 事件中获取当前视频的时长(只有在视频加载完成后才可以获取到)slider_ValueChanged 事件中执行对视频进度的调整xaml: <MediaElement Name="player"Source="e:\MVVMLight (1).wmv" Loaded="player_Loaded" MediaOpened="player_MediaOpened"/><Slider Grid.Row="1" Margin="10" Name="slider" ValueChanged="slider_ValueChanged"/><WrapPanel Grid.Row="1" Margin="0,40,0,0"><TextBlock Name="tb1" Width="120"/><TextBlock Name="tb2" Width="120"/></WrapPanel> 后台代码:private voidplayer_Loaded(object sender, RoutedEventArgs e){ DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(1000); timer.Tick += (ss, ee) => { //显示当前视频进度var ts = player.Position;tb1.Text = string.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);slider.Value =ts.TotalMilliseconds; };timer.Start(); } private voidplayer_MediaOpened(object sender, RoutedEventArgs e){ //显示视频的时长var ts = player.NaturalDuration.TimeSpan; tb2.Text = string.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds); slider.Maximum =ts.TotalMilliseconds; } private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e){ //调整视频进度var ts = TimeSpan.FromMilliseconds(e.NewValue);player.Position = ts; }。

JavaFX在一分钟内编写一个视频播放器

JavaFX在一分钟内编写一个视频播放器

JavaFX在一分钟内编写一个视频播放器首先在Netbeans下新建一个JavaFX空项目。

然后从左边拖一个stage进来Stage是一个javaFX的基础,一个Stage下包含一个sence,就是我们放可视的组件的地方。

改一下大小,取个名字如下:1Stage{2title:"mediaplayer"3scene:Scene{4width:4005height:3506content:[78]9}10}接下来我们到底下的Swing组件里头拖进来一个按钮,并取个名字。

放到content中1SwingButton{2text:"Play"3action:function(){45}6}接下来添加播放器的代码。

因为播放器没有在左边列出来,我们需要import,然后手动写代码。

如下1importjavafx.scene.media.Media;2importjavafx.scene.media.MediaPlayer;3importjavafx.scene.media.MediaView;45//media是用来放电影地址的6varmedia=Media{source:"XX"}78//添加播放器9varplayer=MediaPlayer{media:media,autoPlay:false}接下来我们把各个部分组合起来:注意content里头新加的内容。

1importjavafx.stage.Stage;2importjavafx.scene.Scene;3importjavafx.ext.swing.SwingButton;4importjavafx.scene.media.Media;5importjavafx.scene.media.MediaPlayer;6importjavafx.scene.media.MediaView;78varmedia=Media{source:"XX"}9varplayer=MediaPlayer{media:media,autoPlay:false}1011Stage{12title:"mediaplayer"13scene:Scene{14width:40015height:35016content:[17MediaView{18mediaPlayer:player19}20SwingButton{21text:"player"22action:function(){23player.play()24}25}2627]28}29}如果按下运行,窗口还是半天没出来,请自行更换flv的源。

易语言编写视频播放器

易语言编写视频播放器

易语⾔编写视频播放器
使⽤易语⾔制作视频播放器。

1、启动易语⾔。

2、选择⼯具栏中的“F 程序”,然后在弹出列表中选择“N 新建”。

3、第⼆步搞定后,在弹出的标题为“新建:”的窗⼝中⿏标左键单击“Windows窗⼝程序”,然后⿏标左键单击标题为“确定(o)”的按钮。

4、第三步完成后,在“窗⼝组件箱”中选择“外部组件”中的“播放器组件”。

5、⿏标左键单击“播放器”后,再在"窗⼝设计"那⾥单击⼀下,完成组件的安放。

6、①:在“__启动窗⼝_创建完毕”⼦程序下写代码:播放器1.地址=“”②:利⽤“拖放对象”控件③:利⽤“通⽤对话框”
7、我使⽤的是①,
.版本 2
.⽀持库 wmp9
.程序集窗⼝程序集1
.⼦程序 __启动窗⼝_创建完毕
播放器1.地址=取运⾏⽬录 () + “\0.avi”
8、运⾏易语⾔,看看效果吧!
总结:以上就是⽤易语⾔编写播放器的全部内容,感谢⼤家的阅读和对的⽀持。

WPF下面视频播放器

WPF下面视频播放器

public ICommand SetFullScreenCommand { get; set; }//全屏命令public void SetFullScreen(object param)//全屏方法{if (MediaElement != null){_Rewinding = false;_Forwarding = false;_InrementalValue = 3;//初始化状态var content = Application.Current.Host.Content;//设置屏幕为全屏模式content.IsFullScreen = true;//将VideoBrush的内容设置为MediaElement视频内容VideoBrush objVideoBrush = new VideoBrush();objVideoBrush.SetSource(MyMediaElement);objVideoBrush.Stretch = Stretch.UniformToFill; //调整笔刷大小//在全屏模式下时需要一个Grid作为一个参数传入,//设置其背景内容为VideoBrush面板。

Grid objGrid = (Grid)param; //获取Grid面板参数objGrid.Visibility = Visibility.Visible; //显示GridobjGrid.Background = objVideoBrush; //设置其背景为VideoBrush}}private bool CanSetFullScreen(object param){var content = Application.Current.Host.Content; //仅在非全屏状态时才允许全屏return (!content.IsFullScreen);}界面布局部分就参考了一位网友的,感觉还不错就没改动。

C#在WPF中使用DirectX Dll做MP3播放器

C#在WPF中使用DirectX Dll做MP3播放器

在WPF中使用DirectX Dll做MP3播放器简价:这是一个简单的音乐播放器,可以一次播放一个MP3歌曲。

只包含一个快进,倒带,停止和播放等非常简单的功能。

技术信息:该项目引用以下几个外部的DLL.1)Microsoft.DirectX.AudioVideoPlayback.dll2)Microsoft.DirectX.Direct3D.dll3)Microsoft.DirectX.DirectPlay.dll4)Microsoft.DirectX.DirectSound.dll5)Microsoft.DirectX.dll以下代码是使用C#一步一步教你做一个简单的MP3播放器步骤:1)引用以上介绍的DLL2)引用以下Namespacesusing Microsoft.DirectX.AudioVideoPlayback;using Microsoft.DirectX;using Microsoft.DirectX.Direct3D;using Microsoft.DirectX.DirectPlay;using Microsoft.DirectX.DirectSound;3)全部代码如下namespace SimpleMP3Player{public partial class Form1 : Form{///<summary>/// 1.建立Audio Class///</summary>Audio song;public Form1(){InitializeComponent();}///<summary>/// 2.处理播放事件///</summary>///<param name="sender"></param>///<param name="e"></param>private void playBtn_Click(object sender, EventArgs e){openfile.Filter = "Audio Files(*.wav,*.mp3,*.cda)|*.wav;*.mp3;*.cda";if (openfile.ShowDialog() == DialogResult.OK){this.textBox1.Text = openfile.FileName;song = new Audio(this.textBox1.Text);//songTrack.Maximum = song.Duration;song.Play();//tm.Interval = 60;//tm.Start();//StLabel.Content = "Status : Playing";}}///<summary>/// 3.处理停止事件///</summary>///<param name="sender"></param>///<param name="e"></param>private void stopBtn_Click(object sender, EventArgs e) {try{song.Stop();}catch{}}///<summary>/// 4.处理进进事件///</summary>///<param name="sender"></param>///<param name="e"></param>private void forwBtn_Click(object sender, EventArgs e) {try{song.CurrentPosition += 2;}catch{try{song.CurrentPosition = song.Duration;}catch{}}}///<summary>/// 5.处理倒带事件///</summary>///<param name="sender"></param>///<param name="e"></param>private void rewindBtn_Click(object sender, EventArgs e) {try{song.CurrentPosition -= 2;}catch{try{song.CurrentPosition =0;}catch{}}}}}运行环境:a) Visual Studio 2008 Service Pack 1b) .Net Framework 3.5 + Service Pack 1c) DirectX Compatible Sound Cardd) Speakerse) Few Mp3 Songs to Test。

WPF媒体播放器(MediaElement)实例,实现进度和音量控制

WPF媒体播放器(MediaElement)实例,实现进度和音量控制
所以 mePlayer.NaturalDuration.TimeSpan.TotalSeconds 不能在构造函数或者其他在MediaOpened事件前的方法中调用。
Xaml代码
<Grid> <Grid.RowDefinitions> <RowDefinition Height="180*"/> <RowDefinition Height="89*"/> </Grid.RowDefinitions> <MediaElement x:Name="mediaElement" LoadedBehavior="Manual" Volume="{Binding ElementName=sliderVolume,Path=Value}" Source="F:\MyDocument\视频\COOLUI理念篇.mp4" MediaOpened="mediaElement_MediaOpened" HorizontalAlignment="Left" Height="175" Margin="7,20,0,0" VerticalAlignment="Top" Width="275" Grid.RowSpan="2"/>
HorizontalAlignment="Left" Margin="119,52,0,0" Grid.Row="1" VerticalAlignment="Top" Width="164" Height="18"/> <Label x:Name="label1" Content="进度:" HorizontalAlignment="Left" Margin="73,21,0,0" Grid.Row="1" VerticalAlignment="Top" Height="25" Width="46"/> <Slider x:Name="sliderPosition"

视频播放器的制作

视频播放器的制作

C#中Windows Media Player控件使用实例|方法2009-09-23 09:05:20 来源:原创【大中小】浏览:2241次摘要:Windows Media Player是一种媒体播放器,可以播放当前最流行的音频、视频文件和大多数混合型的多媒体文件。

为了便于程序的开发,Visual Studio 2005集成开发环境提供了Windows Media Player控件,Windows Media Player控件Windows Media Player是一种媒体播放器,可以播放当前最流行的音频、视频文件和大多数混合型的多媒体文件。

为了便于程序的开发,Visual Studio 2005集成开发环境提供了Windows Media Player 控件,并且提供了相关的属性、方法,开发者根据提供的属性、方法完全可以实现Windows Media Player 播放器的所有功能。

在使用Windows Media Player控件进行程序开发前,必须将Windows Media Player控件添加到工具箱中,步骤如下所示。

(1)选择工具箱,并单击鼠标右键,在弹出的快捷菜单中选择“选择项”。

(2)弹出“选择工具箱项”对话框,选择“COM组件”选项卡。

(3)在COM组件列表中,选择名称为“Windows Media Player”,单击【确定】按钮,Windows Media Player控件添加成功,如图1所示。

图1 添加Windows Media Player控件表1和表2介绍Windows Media Player控件提供的主要属性和方法。

表1 Windows Media Player控件主要属性及说明另外,将Windows Media Player控件添加到窗体上,在该控件上单击鼠标右键,弹出“Windows Media Player控件属性”对话框,为Windows Media Player控件提供中文属性对话框,如图2所示。

WPF开发较为完整的音乐播放器(一)

WPF开发较为完整的音乐播放器(一)

WPF开发较为完整的⾳乐播放器(⼀)近来闲来有事,便想到⽤⾃⼰这段时间学习的知识写⼀个⾳乐播放器。

提前声明,我不擅长界⾯,因此做出来的界⾯的却有些次,但不是本系列⽂章的重点。

先讲下我们开发此⾳乐播放器所⽤到的技术:数据绑定、Xml、MediaPlayer类、数据模板等,将在之后陆续讲解。

来阐述下播放器开发的整体思路:构建⾳乐播放类⽤于播放⾳乐,⽤两个控件分别作为播放列表和播放控制,并且利⽤控件模板改变它们的界⾯,利⽤Xml数据读取类XmlListsReader来读取位于存放列表的xml,将歌曲名称、⽂件路径、持续时间歌⼿等信息读取到Product类中,并设置ListBox的ItemSouse为此类,采⽤数据模板显⽰数据。

好了,开始我们第⼀部分的教程--⾳乐播放类的构建。

 话说利⽤WPF播放⾳乐有多种⽅法:MediaPlayer类,SoundPlayer类,以及使⽤DirectX Sound等。

若要选择⼀种功能较多,⽅便易⽤的⽅法,定要属MediaPlayer类了,唯⼀的限制就是需要依赖Windows Media Player(WMP)。

不过在Windows环境下,这⼀限制可以忽略不计,都是系统⾃带的,不是吗?当然,我们可以直接在窗⼝中防置MediaPlayer的操作代码,但是为了更正规化和可维护性,我们将它封装进MusicPlayer类中。

在类的开头,先来定义⼏个私有变量和公有的枚举(表⽰播放器的状态):public enum PlayState : int{stoped = 0,playing = 1,paused = 2}private MediaPlayer player = null;private Uri musicfile;private PlayState state;public Uri MusicFile{set{musicfile = value;}get{return musicfile;}}接下来写构造函数,⼀个带参数(⾳乐⽂件路径),⼀个不带参数的:public MusicPlay(){player = new MediaPlayer();}public MusicPlay(Uri file){Load(file);}构造函数将传⼊的⽂件路径传到Load⽅法中处理,以下是Load⽅法的代码:public void Load(Uri file){player = new MediaPlayer();MusicFile = file;player.Open(musicfile);}Load⽅法中设置了MusicFile(公有变量,指⽰⽂件路径),⽤MediaPlayer的Open⽅法加载了⾳乐⽂件。

WPF视频播放器自做

WPF视频播放器自做

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;using Microsoft.Kinect.Toolkit.Controls; using Microsoft.Kinect;using Microsoft.Kinect.Interop;using Microsoft.Kinect.Toolkit;using System.Windows.Forms;using System.IO;using System.IO.Log;namespace mykinect{///<summary>///MainWindow.xaml的交互逻辑///</summary>publicpartialclass MainWindow : Window{private KinectSensorChooser sensorChooser; private System.Windows.Forms.Timer timer = new Timer() { };string root = "", pathMedia = "";public MainWindow(){InitializeComponent();timer.Tick += new EventHandler(timer_Tick); timer.Enabled = true;SetPlayer(false);Loaded += OnLoaded;InitPath();AddItemToListView();}void timer_Tick(object sender, EventArgs e){//模拟的做一些耗时的操作this.progress.Value =this.mediaElement.Position.Ticks;}privatevoid InitPath(){ApplicationPath ap = new ApplicationPath();root = ap.GetRtfPath("root");pathMedia = root + ap.GetRtfPath("pathMedia"); }//将视频目录下的视频名称添加到ListView中privatevoid AddItemToListView(){string[] files = Directory.GetFiles(pathMedia); foreach (string file in files){this.listView1.Items.Add(file.Substring(file.L astIndexOf('\\') + 1));}}//窗体加载时调用视频,进行播放privatevoid Window_Loaded(object sender, RoutedEventArgs e){MediaElementControl();}List<string>fileNames = new List<string>(); privatevoid MediaElementControl(){this.mediaElement.LoadedBehavior = MediaState.Manual;string[] files = Directory.GetFiles(pathMedia);foreach (string file in files){fileNames.Add(file.Substring(stIndexOf('\\') + 1));}this.mediaElement.Source = new Uri(files[0]);this.mediaElement.Play();}privatevoid mediaElement1_MediaEnded(object sender, RoutedEventArgs e){//获取当前播放视频的名称(格式为:xxx.wmv)string path =this.mediaElement.Source.LocalPath;string currentfileName =path.Substring(stIndexOf('\\') + 1);//对比名称列表,如果相同,则播放下一个,如果播放的是最后一个,则从第一个重新开始播放for (int i = 0; i<fileNames.Count; i++){if (currentfileName == fileNames[i]){if (i == fileNames.Count - 1){this.mediaElement.Source = new Uri(pathMedia + "//" + fileNames[0]);this.mediaElement.Play();}else{this.mediaElement.Source = new Uri(pathMedia + "//" + fileNames[i + 1]);this.mediaElement.Play();}break;}}}//播放列表选择时播放对应视频privatevoid listView1_SelectionChanged(object sender, SelectionChangedEventArgs e){//mediaElement.Stop();//SetPlayer(false);//我想在这里实现暂停的功能string fileName =this.listView1.SelectedValue.ToString(); this.mediaElement.Source = new Uri(pathMedia + "//" + fileName);//this.mediaElement.Play();//mediaElement.Source = newUri(openFileDialog.FileName, 0);progress.Value = 0;playBtn.IsEnabled = true;}privatevoid SetPlayer(bool bVal){stopBtn.IsEnabled = bVal;playBtn.IsEnabled = bVal;}privatevoid PlayerPause(){SetPlayer(true);if (playBtn.Content.ToString() == "Play"){mediaElement.Play();playBtn.Content = "Pause";mediaElement.ToolTip = "Click to Pause";}else{mediaElement.Pause();playBtn.Content = "Play";mediaElement.ToolTip = "Click to Play";}}privatevoid OnLoaded(object sender, RoutedEventArgs e){this.sensorChooser = new KinectSensorChooser();this.sensorChooser.KinectChanged += SensorChooserOnKinectChanged;this.sensorChooserUi.KinectSensorChooser = this.sensorChooser;this.sensorChooser.Start();}privatevoid SensorChooserOnKinectChanged(object sender, KinectChangedEventArgs args){bool error = false;if (args.OldSensor != null){try{args.OldSensor.DepthStream.Range = DepthRange.Default;args.OldSensor.SkeletonStream.EnableTrackingIn NearRange = false;args.OldSensor.DepthStream.Disable();args.OldSensor.SkeletonStream.Disable();}catch (InvalidOperationException){// KinectSensor might enter an invalid state while enabling/disabling streams or stream features.// E.g.: sensor might be abruptly unplugged. error = true;}}if (args.NewSensor != null){try{args.NewSensor.DepthStream.Enable(DepthImageFo rmat.Resolution640x480Fps30);args.NewSensor.SkeletonStream.Enable();try{args.NewSensor.DepthStream.Range =DepthRange.Near;args.NewSensor.SkeletonStream.EnableTrackingIn NearRange = true;args.NewSensor.SkeletonStream.TrackingMode = SkeletonTrackingMode.Seated;}catch (InvalidOperationException){args.NewSensor.DepthStream.Range = DepthRange.Default;args.NewSensor.SkeletonStream.EnableTrackingIn NearRange = false;}}catch (InvalidOperationException){error = true;}}}privatevoid Button_Click(object sender,RoutedEventArgs e){OpenFileDialog openFileDialog =new OpenFileDialog();openFileDialog.Filter ="wmvfiles(*.wmv)|*.wmv|wmvfiles(*.avi)|*.avi";if (openFileDialog.ShowDialog() ==System.Windows.Forms.DialogResult.OK){System.Windows.MessageBox.Show(openFileDialog. FileName);mediaElement.Source =new Uri(openFileDialog.FileName, 0);playBtn.IsEnabled = true;}//MediaElementControl();}privatevoid playBtn_Click(object sender, RoutedEventArgs e){PlayerPause();}privatevoid Grid_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e){if (e.Key == Key.Escape)//Esc键{this.WindowState =System.Windows.WindowState.Normal;this.WindowStyle =System.Windows.WindowStyle.SingleBorderWindow; }}privatevoid Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e){}privatevoid volumeSlider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double>e)//目前就是这里存在bug{this.progress.Maximum =this.mediaElement.NaturalDuration.TimeSpan.Tic ks;this.mediaElement.Position =new TimeSpan((long)this.progress.Value);}privatevoid mediaElement_MouseLeftButtonUp(obje ct sender, MouseButtonEventArgs e){PlayerPause();}privatevoid stopBtn_Click(object sender, RoutedEventArgs e){mediaElement.Stop();playBtn.Content = "Play";SetPlayer(false);playBtn.IsEnabled = true;}}}XAML代码:<Window x:Class="mykinect.MainWindow"xmlns="/winfx/2006 /xaml/presentation"xmlns:x="/winfx/20 06/xaml"xmlns:k="/kinect/2 013"Title="MainWindow" Height="700" Width="1050"> <Grid><k:KinectSensorChooserUI HorizontalAlignment="C enter"VerticalAlignment="Top"Name="sensorChooserUi" /><RectangleFill="#FFF4F4F5"HorizontalAlignment="Left" Height="542" Margin="10,45,0,0"Stroke="Yellow"VerticalAlignment="Top"Width="793"/><MediaElement HorizontalAlignment="Left"Height="542" Name="mediaElement"Margin="10,45,0,0"VerticalAlignment="Top" Width="793"Volume="{Binding ElementName=volumeSlider, Path=Value}"LoadedBehavior="Manual" /><Slider x:Name="progress" Height="22"Margin="10,587,239,0"VerticalAlignment="Top"Va lueChanged="volumeSlider1_ValueChanged"/><Slider x:Name="volumeSlider" Minimum="0" Maximum="1"HorizontalAlignment="Left"Margin="649,619,0,0"VerticalAlignment="Top" Width="154"ValueChanged="Slider_ValueChanged"/ ><Button Content="Open File"HorizontalAlignment="Left" Height="23" Margin="10,614,0,0"VerticalAlignment="Top" Width="127" Click="Button_Click"/><Button x:Name="playBtn"Content="Play"HorizontalAlignment="Left" Height="23"Margin="219,614,0,0"VerticalAlignment="Top"Width="101" Click="playBtn_Click"/><ListView HorizontalAlignment="Left"Height="303" Margin="808,45,0,0"Name="listView1"SelectionMode="Single"IsSynchr onizedWithCurrentItem="{x:Null}"SelectionChang ed="listView1_SelectionChanged" VerticalAlignment="Top" Width="224"><ListView.View><GridView><GridViewColumn/></GridView></ListView.View></ListView><Button x:Name="stopBtn"Content="Stop"HorizontalAlignment="Left" Margin="417,614,0,0"VerticalAlignment="Top" Width="75"RenderTransformOrigin="0.507,1.211" Height="23" Click="stopBtn_Click"/></Grid></Window>ApplicationPath代码:using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml;namespace mykinect{class ApplicationPath{privatereadonlystaticstring ImagePath = Environment.CurrentDirectory + "\\image\\"; privatereadonlystaticstring RtfPath = Environment.CurrentDirectory + "\\rtf\\";XmlDocument xDoc = new XmlDocument();public ApplicationPath(){xDoc.Load(getAppConfigPath());}publicstaticstring getImagePath(){return ImagePath;}publicstaticstring getRtfPath(){return RtfPath;}publicstring getAppConfigPath(){return Environment.CurrentDirectory +"\\App.config";}//获取App.config值publicstring GetRtfPath(string appKey){try{XmlNode xNode;XmlElement xElem;xNode = xDoc.SelectSingleNode("//appSettings");xElem =(XmlElement)xNode.SelectSingleNode("//add[@key ='" + appKey + "']");if (xElem != null){return xElem.GetAttribute("value");}elsereturn"";}catch (Exception){return"";}}}}App.config:<?xml version="1.0" encoding="utf-8"?><configuration><appSettings><add key="root" value="D:\" /><add key="pathMedia" value="英雄时刻\" />//根据需要自己改改就行</appSettings></configuration>。

用wpf做的音乐播放器

用wpf做的音乐播放器

Wpf之音乐播放器程序界面:前台代码:<Window x:Class="音°?乐¤?播£¤放¤?器¡Â.MainWi ndow"xmlns="/winfx/2006/xaml/presentation"xmlns:x="/winfx/2006/xaml"Title="音°?乐¤?播£¤放¤?器¡Â" Height="361" Width="489" Loaded="Wi ndow_Loaded" Name="音°?乐¤?播£¤放¤?器¡Â"><Grid Background="Black"><Grid.ColumnDefinitions><ColumnDefinition Width="340*"></C olumnDefinition><ColumnDefinition Width="127*"></C olumnDefinition></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="*"></R owDefinition><RowDefinition Height="102"></RowDefinition></Grid.RowDefinitions><Grid Grid.Column="0" Grid.Row="0" Background="Black"><Grid.RowDefinitions><RowDefinition Height="*"></RowDefinition><RowDefinition Height="38"></RowDefinition></Grid.RowDefinitions><Grid Grid.Row="1" Background="Black"><Grid.ColumnDefinitions><ColumnDefinition Width="60.5"></ColumnDefinition><ColumnDefinition Width="60.5"></ColumnDefinition><ColumnDefinition Width="*" /></Grid.ColumnDefinitions><StackPanel Orientati on="Vertical" Grid.Column="2"><Label Content="当Ì¡À前¡ã播£¤放¤?:êo" Height="20" FontSize="10" Name="lable1" VerticalAlignment="Top" Foreground="Red"></Label><Slider Name="slider1"Value="{BindingElementName=me,Path=me.position,Mode=TwoWay}" VerticalAlignment="Center"ValueChanged="slider1_ValueChanged"></Slider></StackPanel><Label Name="txtruntime"Grid.Column="0" Horizontal Alignment="Stretch" VerticalAlignment="Center" FontSize="12.5" Foreground="Red"></Label><Label Name="txttataltime" Grid.Column="1" VerticalAlignment="Center"FontSize="12.5" Foreground="Red"></Label></Grid><MediaElement Name="me" Grid.Column="0" Grid.Row="0"LoadedBehavior="Manual" MediaEnded="me_MediaEnded" /></Grid><ListBox Name="listBox1" Grid.Column="1" Grid.RowSpan="2"SelectionChanged="li stBox1_SelectionChanged" MouseDoubleClick="listBox1_MouseDoubleClick_1" Foreground="AntiqueWhite" Background="Black"BorderBrush="Blue" BorderThickness="5"><ListBox.ContextMenu><ContextMenu><MenuItem Header="添¬¨ª加¨®单Ì£¤个?媒?体¬?文?件t" Click="MenuItem_Click" ></MenuItem><MenuItem Header="删¦?除y单Ì£¤个?媒?体¬?文?件t" Click="MenuItem_Click_1"></MenuItem><MenuItem Header="清?空?列¢D表À¨ª" Click="MenuItem_Click_2"></MenuItem></ContextMenu></ListBox.ContextMenu></ListBox><Grid Grid.Row="1" Grid.Column="0"><Grid.ColumnDefinitions><ColumnDefinition></ColumnDefinition><ColumnDefinition></ColumnDefinition><ColumnDefinition></ColumnDefinition></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition></RowDefinition><RowDefinition></RowDefinition><RowDefinition></RowDefinition></Grid.RowDefinitions><Button Background="Black" Grid.Row="1" Content="快¨¬退ª?" Name="btnback"Click="btnback_Click_1" Foreground="Blue" BorderBrush="Blue" BorderThickness="5" /><Button Background="Black" Content="快¨¬进?" Grid.Column="2" Grid.Row="1"Name="btngo" Click="btngo_Click_1"Foreground="Blue" BorderBrush="Blue" BorderThickness="5"/> <Button Background="Black" Content="播£¤放¤?" Grid.Row="2" Grid.Column="1"Name="btnplayhold" Click="btnplayhold_Click" Foreground="Blue" BorderBrush="Blue" BorderThickness="5" ></Button><Button Background="Black" Content="打䨰开a" Grid.Row="2" Name="btnopen"Grid.Column="0" Click="btnopen_Click" Foreground="Blue" B orderBrush="Blue"BorderThickness="5"></Button><Button Background="Black" Content="退ª?出?" Grid.Column="2" Name="btnclose"Grid.Row="2" Click="btnclose_Click" Foreground="Blue" BorderBrush="Blue"BorderThickness="5" ></Button><Button Background="Black" Content="上¦?一°?曲¨²" Name="btnfor" Click="btnfor_Click" Grid.Row="0" Grid.Column="0 " Foreground="Blue" BorderBrush="Blue" BorderThickness="5"></Button><Button Background="Black" Content="下?一°?曲¨²" Grid.Column="2" Name="btnnext" Click="btnnext_Click" Foreground="Blue" BorderBrush="Blue" BorderThickness="5" ></Button> <Slider Grid.Column="1"Name="slidvolume"Grid.Row="1"Maximum="1" Minimum="0" VerticalContentAlignment="Center" HorizontalContentAlignment="Stretch" ValueChanged="slidvol ume_ValueChanged" SmallChange="0.1" VerticalAlignment="Center" LargeChange="0.1" /><Button Background="Black" Content="列¢D表À¨ª循-环¡¤" Grid.Column="1" Grid.Row="0" Name="btnplaymode" Click="btnplaymode_Click" Foreground="Blue" BorderBrush="Blue" BorderThickness="5"/></Grid></Grid></Wi ndow>后台源代码:using System;using System.Collections.Generic;using System.Linq;using System.Text;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;using System.Windows.Forms;using System.IO;using System.Runtime;using System.Windows.Media.Animation;using System.Threading;namespace音°?乐¤?播£¤放¤?器¡Â{///<summary>/// MainWindow.xaml 的Ì?交?互£¤逻?辑-///</summary>public partial class MainWindow : Window{List<string> s = new List<string>();byte[] bs;List<string> str8 = null;private bool ?flag = null;private bool? flag1;FolderBrowserDialog fbd = new FolderBrowserDialog();StringBuilder sb = new StringBuilder();private string[] strm = null;public MainWindow(){InitializeComponent();}private void Window_Loaded(object sender, RoutedEventArgs e){flag = null;flag1=null;str8 = new List<string>();slidvolume.Value =0.3;me.Volume = 0.3;txttataltime.Content = me.Position.ToString();txtruntime.Content = me.Positi on.ToString();listBox1.Items.Clear();FileStream fs1 = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D 表À¨ª.txt", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);byte[] bt = new byte[fs1.Length];fs1.Read(bt, 0, bt.Length);string str = Encodi ng.Default.GetString(bt);string[] str4 = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);s = str4.Distinct().ToList();for (int i = 0; i <= s.Count - 1; i++){if (s[i].LastIndexOf("\\")>=0){listBox1.Items.Add(s[i].Substring(s[i].LastIndexOf("\\") + 1));str8.Add(s[i].Substring(0, s[i].LastIndexOf("\\")));}}System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();t.Enabled = true;t.Tick += new EventHandler(t_Tick);t.Interval = 1100;t.Start();}private void btnfor_Click(object sender, RoutedEventArgs e){try{if (flag1 ==null){listBox1.SelectedIndex--;}if(flag1==true){Random rnd = new Random();listBox1.SelectedIndex = rnd.Next(0, listBox1.Items.Count - 1);}if(flag1==false){}if (listBox1.SelectedIndex < 0){(listBox1.SelectedIndex) = (listBox1.Items.Count - 1);}musicplay();}catch { System.Wi ndows.Forms.MessageBox.Show("请?选?择?歌¨¨曲¨²"); } }private void btnnext_Click(object sender, RoutedEventArgs e){if (flag1 == null){if (listBox1.SelectedIndex <listBox1.Items.Count - 1){listBox1.SelectedIndex++;musicplay();return;}if (listBox1.SelectedIndex >= listBox1.Items.Count - 1){(listBox1.SelectedIndex) = 0;}}if (flag1 == true){Random rnd = new Random();listBox1.SelectedIndex = rnd.Next(0, listBox1.Items.Count - 1);}if (flag1 == false){}musicplay();}private void btnplayhold_Click(object sender, RoutedEventArgs e){if (flag == true){btnplayhold.Content = "暂Y停ª¡ê";me.Pause();flag = false;return;}else{if( flag==false ){me.Play();btnplayhold.Content = "播£¤放¤?";flag = true;return;}else{btnplayhold.Content = "播£¤放¤?";musicplay();return;}}}private void btnopen_Click(object sender, RoutedEventArgs e){fbd.ShowDialog();byte[] bs;string[] str={"*.mp3","*.rmvb","*.jpg","*.avi","*.mp4","*.rm"};foreach (string s in str){if (fbd.SelectedPath == ""){System.Windows.Forms.MessageBox.Show("请?选?择?正y确¨¡¤的Ì?文?件t夹D");return;}strm = Directory.GetFiles(fbd.SelectedPath, s);str8.Add(fbd.SelectedPath);for (int i = 0; i <= strm.Length - 1; i++){sb.Append(strm[i]);sb.Append("\r\n");listBox1.Items.Add(strm[i].Substring(strm[i].LastIndexOf("\\") + 1));}}FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory+"\\歌¨¨曲¨²列¢D表À¨ª.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);bs = Encoding.Default.GetBytes(sb.ToString());fs.Write(bs, 0, bs.Length);fs.Flush();fs.Close();if (listBox1.Items.Count == 0){System.Windows.Forms.MessageB ox.Show("请?选?择?正y确¨¡¤的Ì?文?件t夹D");}}private void btncl ose_Click(object sender, RoutedEventArgs e){this.Close();}private void listBox1_MouseDoubleClick_1(object sender, MouseButtonEventArgs e){musicplay();}private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e){flag = null;}private void btngo_Click_1(object sender, RoutedEventArgs e){if(listBox1.SelectedIndex+1!=0){TimeSpan ts = new TimeSpan(0,0,3);me.Position = me.Position.Add(ts);}}private void btnback_Click_1(object sender, RoutedEventArgs e){if(listBox1.SelectedIndex+1!=0){TimeSpan ts = new TimeSpan(0, 0, 3);me.Position = me.Position-ts;}}private void slidvolume_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) {me.ScrubbingEnabled = true;me.Volume = slidvolume.Value;}private void musicplay(){Thread.Sleep(1000);me.Close();if (listBox1.SelectedItem.ToString() ==null){System.Windows.Forms.MessageBox.Show("请?选?择?歌¨¨曲¨²");return;}for (int i = 0; i <= str8.Count-1;i++ ){if (str8[i] !=""){if (File.Exists(str8[i] + "\\" + listBox1.SelectedItem.ToString()) == true){lable1.Content = "当Ì¡À前¡ã播£¤放¤?:êo" + listB ox1.SelectedItem.ToString();lable1.Width = listBox1.SelectedItem.ToString().Length * 20;me.Source = new Uri(str8[i] + "\\" + listB ox1.SelectedItem.ToString().ToString(), UriKind.RelativeOrAbsolute);me.Play();btnplayhold.Content = "播£¤放¤?";flag = true;return;}else {TimeSpan ts = new TimeSpan(0,0,0);me.Position = ts;lable1.Content = "当Ì¡À前¡ã播£¤放¤?:êo 歌¨¨曲¨²不?存ä?在¨²,请?从䨮新?加¨®载?!ê?!ê?!ê?" ;lable1.Width = listB ox1.SelectedItem.ToString().Length *40;txttataltime.Content = "00:00:00";}}}}private void t_Tick(object sender, EventArgs e){string str = me.NaturalDuration.ToString();if (me.Position == me.NaturalDurati on){me.Close();string[] str3 = str.Split(':');double a = Convert.ToDouble(str3[0]);double b = Convert.ToDouble(str3[1]);double c = Convert.ToDouble(str3[2]);slider1.Maximum = (a * 3600 + b * 60 + c);}if (str !="Automatic"){string[] str3 = str.Split(':');double a = Convert.ToDouble(str3[0]);double b = Convert.ToDouble(str3[1]);double c = Convert.ToDouble(str3[2]);slider1.Maximum = (a * 3600 + b * 60 + c);txttataltime.Content = me.NaturalDuration.ToString();}if (str == "Automatic"){str = me.Position.ToString();}slider1.Minimum = 0;txtruntime.Content = me.Position.ToString();string s = me.Position.ToString();string[] str2 = s.Split(':');double d = Convert.ToDouble(str2[0]);double g = Convert.ToDouble(str2[1]);double f = Convert.ToDouble(str2[2]);slider1.Value = (d * 3600 + g * 60 + f);}private void btnplaymode_Click(object sender, RoutedEventArgs e){if (flag1 == null){btnplaymode.Content = "随?机¨²播£¤放¤?";flag1 = true;return;}if (flag1 == true){btnplaymode.Content = "单Ì£¤曲¨²循-环¡¤";flag1 = false;return;}if (flag1 == false){btnplaymode.Content = "列¢D表À¨ª循-环¡¤";flag1 = null;return;}}private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e){me.Scrubbi ngEnabled = true;me.Position = TimeSpan.FromSeconds(slider1.Value);}private void MenuItem_Click(object sender, RoutedEventArgs e){OpenFileDialog ofp = new OpenFileDialog();ofp.Multi select = true;ofp.ShowDialog();if (ofp.FileName == ""){System.Windows.Forms.MessageBox.Show("请?选?择?正y确¨¡¤的Ì?文?件t");return;}for (int i = 0; i <= ofp.FileNames.Count() - 1; i++){sb.Append(ofp.FileNames[i]);sb.Append("\r\n");if (ofp.SafeFileNames[i] != ""){listBox1.Items.Add(ofp.SafeFileNames[i]);str8.Add(ofp.FileNames[i].Substring(0, ofp.FileNames[i].LastIndexOf("\\") + 1));}}FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D表À¨ª.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);bs = Encoding.Default.GetBytes(sb.ToString());fs.Write(bs, 0, bs.Length);fs.Flush();fs.Close();}private void MenuItem_Click_1(object sender, RoutedEventArgs e){try{FileStream fs1 = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D表À¨ª.txt", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);byte[] bt = new byte[fs1.Length];fs1.Read(bt, 0, bt.Length);fs1.Dispose();string str = Encoding.Default.GetString(bt);string[] s = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);List<string> list = new List<string>(s);if (listBox1.SelectedItem != null){for (int i = 0; i < s.Length - 1; i++){if (s[i].Contains(listBox1.SelectedItem.ToString())){list.RemoveAt(i);}}}s = (string[])list.ToArray();FileInfo file = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D表À¨ª.txt");file.Refresh();file.Delete();List<string> li = new List<string>();li=s.Distinct().ToList();StringBuilder sb = new StringBuilder();for (int i = 0; i <= li.Count - 1; i++){sb.Append(li[i]);sb.Append("\r\n");}FileStream fs2 = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D表À¨ª.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);bs = Encoding.Default.GetBytes(sb.ToString());fs2.Write(bs, 0, bs.Length);fs2.Flush();fs2.Close();}catch {}listBox1.Items.Remove(listBox1.SelectedItem);}private void MenuItem_Click_2(object sender, RoutedEventArgs e){me.Stop();listBox1.Items.Clear();FileInfo file = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D表À¨ª.txt");file.Refresh();file.Delete();}private void me_MediaEnded(object sender, RoutedEventArgs e){if (flag1 == null){if (listBox1.SelectedIndex == listBox1.Items.Count - 1){listBox1.SelectedIndex = 0;}else{listBox1.SelectedIndex++;}musicplay();}if (flag1 == true){Random rnd = new Random();listBox1.SelectedIndex = rnd.Next(0, listBox1.Items.Count - 1);musicplay();}if (flag1 == false){musicplay();}}}}。

自定义视频播放器(功能包括:播放暂停,全屏,跳播)

自定义视频播放器(功能包括:播放暂停,全屏,跳播)

⾃定义视频播放器(功能包括:播放暂停,全屏,跳播)最终效果:1、demo结构loading.gif:百度loading.gif选择⼀张下载2、index.html 功能包括:播放/暂停,全屏,跳播<!DOCTYPE html><html><head><meta charset="utf-8"><title>⾃定义视频播放器</title><link rel="stylesheet" href="./css/font-awesome.min.css"><link rel="stylesheet" href="./css/index.css"></head><body><h3 class="player-title">视频播放器</h3><div class="player-container"><video src="./mp4/test.mp4"></video><div class="controls-container"><!-- 播放/暂停 --><a href="javascript:;" class="switch fa fa-play"></a><!-- 全屏 --><a href="javascript:;" class="expand fa fa-expand"></a><!-- 进度条 --><div class="progress"><!-- 进度条底⾊ --><div class="bar"></div><!-- 进度条最外层,⽤于事件控制 --><div class="loaded"></div><!-- 已加载 --><div class="current-progress"></div><!-- 已播放 --></div><!-- 当前播放时间, 视频总长 --><div class="time"><span class="current-time">00:00:00</span>\<span class="total-time">00:00:00</span></div></div></div><script type="text/javascript">// 播放器const video = document.querySelector('video');// "播放/暂停"切换按钮const switchBtn = document.querySelector('.switch');// 当前播放时间spanconst currentTimeSpan = document.querySelector('.current-time')// 视频总时长const totalTimeSpan = document.querySelector('.total-time')// 当前播放进度条const currentProgress = document.querySelector('.current-progress')// 获取进度条最外层,⽤于事件控制const bar = document.querySelector('.bar');// 实现"播放/暂停"switchBtn.onclick = function() {// 播放与暂停的切换if (video.paused) {video.play();} else {video.pause();}// 播放与暂停图标的切换this.classList.toggle('fa-pause');this.classList.toggle('fa-play');}// 实现"全屏"const playerContainer = document.querySelector('.player-container');document.querySelector('.expand').onclick = function() {if(playerContainer.requestFullScreen){playerContainer.requestFullScreen();} else if(playerContainer.webkitRequestFullScreen){playerContainer.webkitRequestFullScreen();} else if(playerContainer.mozRequestFullScreen){playerContainer.mozRequestFullScreen();} else if(playerContainer.msRequestFullScreen){playerContainer.msRequestFullScreen();}}// 当视频⽂件可以播放时触发// 当跳播时,修改了video.currentTime,也会触发该事件video.oncanplay = function() {console.log('触发oncanplay事件, video.currentTime=', video.currentTime) if (video.currentTime === 0) {setTimeout(function() {console.log('视频缓存完成,可以播放了。

WPF基于VLC播放器的视频控件

WPF基于VLC播放器的视频控件

WPF基于VLC播放器的视频控件这⾥要实现的就是基于Vlc.DotNet.Wpf调⽤VLC播放器,完成⼀个简单的WPF视频播放控件。

Vlc.DotNet.Wpf 初始化播放器控件通过Nuget安装Vlc.DotNet.Wpf,⾃动添加相关引⽤。

这⾥需要注意引⽤的nuget版本。

不同版本dll的内部层级不同,体现在代码上就是调⽤⽅式的区别了Install-Package Vlc.DotNet.Wpf -Version 3.1.0Vlc.DotNet.CoreVlc.DotNet.Core.InteropsVlc.DotNet.Wpf初始化VLC控件关键代码:VlcControl vlcControl = null;string VLCPath = "VLC播放器安装⽬录";void InitVLCPlayer(string url){this.vlcControl = new VlcControl();this.ControlContainer.Content = vlcControl;this.vlcControl.SourceProvider.CreatePlayer(new System.IO.DirectoryInfo(VLCPath));if (!string.IsNullOrWhiteSpace(url)){vlcControl.SourceProvider.MediaPlayer.Play(new Uri(url));}}1. 调⽤VLC播放器时,需要注意播放器版本是X64的还是X86的。

相应的需要修改当前应⽤程序的平台为对于版本。

⽐如我安装的是X64的播放器,则需要在配置管理器中修改配置为X64。

2. 单独提取下⾯⼏个VLC播放器的⽂件也可以实现常⽤的API和Event//暂停this.vlcControl.SourceProvider.MediaPlayer.Pause();//播放this.vlcControl.SourceProvider.MediaPlayer.Play();//⾳量控制this.vlcControl.SourceProvider.MediaPlayer.Audio.Volume = 100;//倍数控制this.vlcControl.SourceProvider.MediaPlayer.Rate = 1.5f;//视频长度单位:msvar len = this.vlcControl.SourceProvider.MediaPlayer.Length;//全屏this.vlcControl.SourceProvider.MediaPlayer.Video.FullScreen = true;//进度变化事件this.vlcControl.SourceProvider.MediaPlayer.PositionChanged += MediaPlayer_PositionChanged;通过这些API和相关的事件绑定,基本上⼀个简单视频播放控件就出来了。

WPF播放视频

WPF播放视频

WPF播放视频在现在的项⽬中需要使⽤到播放视频的功能,本来打算使⽤VLC来做的。

后来发现WPF 4.0之后新增了MediaElement类,可以实现视频播放。

<Grid><Grid.RowDefinitions><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions><Grid Background="Black"><MediaElement x:Name="MediaPlayer" LoadedBehavior="Manual" MediaOpened="MediaPlayer_MediaOpened"/></Grid><Grid Grid.Row="1"><Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><StackPanel Grid.Column="1" Orientation="Horizontal"><Button x:Name="ButtonOpen" Click="ButtonOpen_Click" Content="Open..." Width="100" Height="25" Margin="5"/><Button x:Name="ButtonPlay" Click="ButtonPlay_Click" Content="Play" Width="100" Height="25" Margin="5"/><Button x:Name="ButtonStop" Click="ButtonStop_Click" Content="Stop" Width="100" Height="25" Margin="5"/><Button x:Name="ButtonForward" Click="ButtonForward_Click" Content="Forward" Width="100" Height="25" Margin="5"/><Button x:Name="ButtonBack" Click="ButtonBack_Click" Content="Back" Width="100" Height="25" Margin="5"/></StackPanel></Grid></Grid>private string _videoPath;public MainWindow(){InitializeComponent();}private void ButtonOpen_Click(object sender, RoutedEventArgs e){OpenFileDialog dialog = new OpenFileDialog();dialog.Filter = "Video File(*.avi;*.mp4;*.mkv;*.wav;*.rmvb)|*.avi;*.mp4;*.mkv;*.wav;*.rmvb|All File(*.*)|*.*";if(dialog.ShowDialog().GetValueOrDefault()){_videoPath = dialog.FileName;}}private void ButtonPlay_Click(object sender, RoutedEventArgs e){MediaPlayer.Source = new Uri(_videoPath);MediaPlayer.Play();}private void ButtonStop_Click(object sender, RoutedEventArgs e){MediaPlayer.Stop();}private void ButtonForward_Click(object sender, RoutedEventArgs e){MediaPlayer.Position = MediaPlayer.Position + TimeSpan.FromSeconds(20);}private void ButtonBack_Click(object sender, RoutedEventArgs e){MediaPlayer.Position = MediaPlayer.Position - TimeSpan.FromSeconds(20);}private void MediaPlayer_MediaOpened(object sender, RoutedEventArgs e){// Get the lenght of the videoint duration = MediaPlayer.NaturalDuration.TimeSpan.Seconds;}这样就可以简单的实现对视频的播放,暂停,快进,快退等。

用wpf做的音乐播放器

用wpf做的音乐播放器

Wpf之音乐播放器程序界面:前台代码:<Window x:Class="音°?乐¤?播£¤放¤?器¡Â.MainWi ndow"xmlns="/winfx/2006/xaml/presentation"xmlns:x="/winfx/2006/xaml"Title="音°?乐¤?播£¤放¤?器¡Â" Height="361" Width="489" Loaded="Wi ndow_Loaded" Name="音°?乐¤?播£¤放¤?器¡Â"><Grid Background="Black"><Grid.ColumnDefinitions><ColumnDefinition Width="340*"></C olumnDefinition><ColumnDefinition Width="127*"></C olumnDefinition></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="*"></R owDefinition><RowDefinition Height="102"></RowDefinition></Grid.RowDefinitions><Grid Grid.Column="0" Grid.Row="0" Background="Black"><Grid.RowDefinitions><RowDefinition Height="*"></RowDefinition><RowDefinition Height="38"></RowDefinition></Grid.RowDefinitions><Grid Grid.Row="1" Background="Black"><Grid.ColumnDefinitions><ColumnDefinition Width="60.5"></ColumnDefinition><ColumnDefinition Width="60.5"></ColumnDefinition><ColumnDefinition Width="*" /></Grid.ColumnDefinitions><StackPanel Orientati on="Vertical" Grid.Column="2"><Label Content="当Ì¡À前¡ã播£¤放¤?:êo" Height="20" FontSize="10" Name="lable1" VerticalAlignment="Top" Foreground="Red"></Label><Slider Name="slider1"Value="{BindingElementName=me,Path=me.position,Mode=TwoWay}" VerticalAlignment="Center"ValueChanged="slider1_ValueChanged"></Slider></StackPanel><Label Name="txtruntime"Grid.Column="0" Horizontal Alignment="Stretch" VerticalAlignment="Center" FontSize="12.5" Foreground="Red"></Label><Label Name="txttataltime" Grid.Column="1" VerticalAlignment="Center"FontSize="12.5" Foreground="Red"></Label></Grid><MediaElement Name="me" Grid.Column="0" Grid.Row="0"LoadedBehavior="Manual" MediaEnded="me_MediaEnded" /></Grid><ListBox Name="listBox1" Grid.Column="1" Grid.RowSpan="2"SelectionChanged="li stBox1_SelectionChanged" MouseDoubleClick="listBox1_MouseDoubleClick_1" Foreground="AntiqueWhite" Background="Black"BorderBrush="Blue" BorderThickness="5"><ListBox.ContextMenu><ContextMenu><MenuItem Header="添¬¨ª加¨®单Ì£¤个?媒?体¬?文?件t" Click="MenuItem_Click" ></MenuItem><MenuItem Header="删¦?除y单Ì£¤个?媒?体¬?文?件t" Click="MenuItem_Click_1"></MenuItem><MenuItem Header="清?空?列¢D表À¨ª" Click="MenuItem_Click_2"></MenuItem></ContextMenu></ListBox.ContextMenu></ListBox><Grid Grid.Row="1" Grid.Column="0"><Grid.ColumnDefinitions><ColumnDefinition></ColumnDefinition><ColumnDefinition></ColumnDefinition><ColumnDefinition></ColumnDefinition></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition></RowDefinition><RowDefinition></RowDefinition><RowDefinition></RowDefinition></Grid.RowDefinitions><Button Background="Black" Grid.Row="1" Content="快¨¬退ª?" Name="btnback"Click="btnback_Click_1" Foreground="Blue" BorderBrush="Blue" BorderThickness="5" /><Button Background="Black" Content="快¨¬进?" Grid.Column="2" Grid.Row="1"Name="btngo" Click="btngo_Click_1"Foreground="Blue" BorderBrush="Blue" BorderThickness="5"/> <Button Background="Black" Content="播£¤放¤?" Grid.Row="2" Grid.Column="1"Name="btnplayhold" Click="btnplayhold_Click" Foreground="Blue" BorderBrush="Blue" BorderThickness="5" ></Button><Button Background="Black" Content="打䨰开a" Grid.Row="2" Name="btnopen"Grid.Column="0" Click="btnopen_Click" Foreground="Blue" B orderBrush="Blue"BorderThickness="5"></Button><Button Background="Black" Content="退ª?出?" Grid.Column="2" Name="btnclose"Grid.Row="2" Click="btnclose_Click" Foreground="Blue" BorderBrush="Blue"BorderThickness="5" ></Button><Button Background="Black" Content="上¦?一°?曲¨²" Name="btnfor" Click="btnfor_Click" Grid.Row="0" Grid.Column="0 " Foreground="Blue" BorderBrush="Blue" BorderThickness="5"></Button><Button Background="Black" Content="下?一°?曲¨²" Grid.Column="2" Name="btnnext" Click="btnnext_Click" Foreground="Blue" BorderBrush="Blue" BorderThickness="5" ></Button> <Slider Grid.Column="1"Name="slidvolume"Grid.Row="1"Maximum="1" Minimum="0" VerticalContentAlignment="Center" HorizontalContentAlignment="Stretch" ValueChanged="slidvol ume_ValueChanged" SmallChange="0.1" VerticalAlignment="Center" LargeChange="0.1" /><Button Background="Black" Content="列¢D表À¨ª循-环¡¤" Grid.Column="1" Grid.Row="0" Name="btnplaymode" Click="btnplaymode_Click" Foreground="Blue" BorderBrush="Blue" BorderThickness="5"/></Grid></Grid></Wi ndow>后台源代码:using System;using System.Collections.Generic;using System.Linq;using System.Text;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;using System.Windows.Forms;using System.IO;using System.Runtime;using System.Windows.Media.Animation;using System.Threading;namespace音°?乐¤?播£¤放¤?器¡Â{///<summary>/// MainWindow.xaml 的Ì?交?互£¤逻?辑-///</summary>public partial class MainWindow : Window{List<string> s = new List<string>();byte[] bs;List<string> str8 = null;private bool ?flag = null;private bool? flag1;FolderBrowserDialog fbd = new FolderBrowserDialog();StringBuilder sb = new StringBuilder();private string[] strm = null;public MainWindow(){InitializeComponent();}private void Window_Loaded(object sender, RoutedEventArgs e){flag = null;flag1=null;str8 = new List<string>();slidvolume.Value =0.3;me.Volume = 0.3;txttataltime.Content = me.Position.ToString();txtruntime.Content = me.Positi on.ToString();listBox1.Items.Clear();FileStream fs1 = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D 表À¨ª.txt", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);byte[] bt = new byte[fs1.Length];fs1.Read(bt, 0, bt.Length);string str = Encodi ng.Default.GetString(bt);string[] str4 = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);s = str4.Distinct().ToList();for (int i = 0; i <= s.Count - 1; i++){if (s[i].LastIndexOf("\\")>=0){listBox1.Items.Add(s[i].Substring(s[i].LastIndexOf("\\") + 1));str8.Add(s[i].Substring(0, s[i].LastIndexOf("\\")));}}System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();t.Enabled = true;t.Tick += new EventHandler(t_Tick);t.Interval = 1100;t.Start();}private void btnfor_Click(object sender, RoutedEventArgs e){try{if (flag1 ==null){listBox1.SelectedIndex--;}if(flag1==true){Random rnd = new Random();listBox1.SelectedIndex = rnd.Next(0, listBox1.Items.Count - 1);}if(flag1==false){}if (listBox1.SelectedIndex < 0){(listBox1.SelectedIndex) = (listBox1.Items.Count - 1);}musicplay();}catch { System.Wi ndows.Forms.MessageBox.Show("请?选?择?歌¨¨曲¨²"); } }private void btnnext_Click(object sender, RoutedEventArgs e){if (flag1 == null){if (listBox1.SelectedIndex <listBox1.Items.Count - 1){listBox1.SelectedIndex++;musicplay();return;}if (listBox1.SelectedIndex >= listBox1.Items.Count - 1){(listBox1.SelectedIndex) = 0;}}if (flag1 == true){Random rnd = new Random();listBox1.SelectedIndex = rnd.Next(0, listBox1.Items.Count - 1);}if (flag1 == false){}musicplay();}private void btnplayhold_Click(object sender, RoutedEventArgs e){if (flag == true){btnplayhold.Content = "暂Y停ª¡ê";me.Pause();flag = false;return;}else{if( flag==false ){me.Play();btnplayhold.Content = "播£¤放¤?";flag = true;return;}else{btnplayhold.Content = "播£¤放¤?";musicplay();return;}}}private void btnopen_Click(object sender, RoutedEventArgs e){fbd.ShowDialog();byte[] bs;string[] str={"*.mp3","*.rmvb","*.jpg","*.avi","*.mp4","*.rm"};foreach (string s in str){if (fbd.SelectedPath == ""){System.Windows.Forms.MessageBox.Show("请?选?择?正y确¨¡¤的Ì?文?件t夹D");return;}strm = Directory.GetFiles(fbd.SelectedPath, s);str8.Add(fbd.SelectedPath);for (int i = 0; i <= strm.Length - 1; i++){sb.Append(strm[i]);sb.Append("\r\n");listBox1.Items.Add(strm[i].Substring(strm[i].LastIndexOf("\\") + 1));}}FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory+"\\歌¨¨曲¨²列¢D表À¨ª.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);bs = Encoding.Default.GetBytes(sb.ToString());fs.Write(bs, 0, bs.Length);fs.Flush();fs.Close();if (listBox1.Items.Count == 0){System.Windows.Forms.MessageB ox.Show("请?选?择?正y确¨¡¤的Ì?文?件t夹D");}}private void btncl ose_Click(object sender, RoutedEventArgs e){this.Close();}private void listBox1_MouseDoubleClick_1(object sender, MouseButtonEventArgs e){musicplay();}private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e){flag = null;}private void btngo_Click_1(object sender, RoutedEventArgs e){if(listBox1.SelectedIndex+1!=0){TimeSpan ts = new TimeSpan(0,0,3);me.Position = me.Position.Add(ts);}}private void btnback_Click_1(object sender, RoutedEventArgs e){if(listBox1.SelectedIndex+1!=0){TimeSpan ts = new TimeSpan(0, 0, 3);me.Position = me.Position-ts;}}private void slidvolume_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) {me.ScrubbingEnabled = true;me.Volume = slidvolume.Value;}private void musicplay(){Thread.Sleep(1000);me.Close();if (listBox1.SelectedItem.ToString() ==null){System.Windows.Forms.MessageBox.Show("请?选?择?歌¨¨曲¨²");return;}for (int i = 0; i <= str8.Count-1;i++ ){if (str8[i] !=""){if (File.Exists(str8[i] + "\\" + listBox1.SelectedItem.ToString()) == true){lable1.Content = "当Ì¡À前¡ã播£¤放¤?:êo" + listB ox1.SelectedItem.ToString();lable1.Width = listBox1.SelectedItem.ToString().Length * 20;me.Source = new Uri(str8[i] + "\\" + listB ox1.SelectedItem.ToString().ToString(), UriKind.RelativeOrAbsolute);me.Play();btnplayhold.Content = "播£¤放¤?";flag = true;return;}else {TimeSpan ts = new TimeSpan(0,0,0);me.Position = ts;lable1.Content = "当Ì¡À前¡ã播£¤放¤?:êo 歌¨¨曲¨²不?存ä?在¨²,请?从䨮新?加¨®载?!ê?!ê?!ê?" ;lable1.Width = listB ox1.SelectedItem.ToString().Length *40;txttataltime.Content = "00:00:00";}}}}private void t_Tick(object sender, EventArgs e){string str = me.NaturalDuration.ToString();if (me.Position == me.NaturalDurati on){me.Close();string[] str3 = str.Split(':');double a = Convert.ToDouble(str3[0]);double b = Convert.ToDouble(str3[1]);double c = Convert.ToDouble(str3[2]);slider1.Maximum = (a * 3600 + b * 60 + c);}if (str !="Automatic"){string[] str3 = str.Split(':');double a = Convert.ToDouble(str3[0]);double b = Convert.ToDouble(str3[1]);double c = Convert.ToDouble(str3[2]);slider1.Maximum = (a * 3600 + b * 60 + c);txttataltime.Content = me.NaturalDuration.ToString();}if (str == "Automatic"){str = me.Position.ToString();}slider1.Minimum = 0;txtruntime.Content = me.Position.ToString();string s = me.Position.ToString();string[] str2 = s.Split(':');double d = Convert.ToDouble(str2[0]);double g = Convert.ToDouble(str2[1]);double f = Convert.ToDouble(str2[2]);slider1.Value = (d * 3600 + g * 60 + f);}private void btnplaymode_Click(object sender, RoutedEventArgs e){if (flag1 == null){btnplaymode.Content = "随?机¨²播£¤放¤?";flag1 = true;return;}if (flag1 == true){btnplaymode.Content = "单Ì£¤曲¨²循-环¡¤";flag1 = false;return;}if (flag1 == false){btnplaymode.Content = "列¢D表À¨ª循-环¡¤";flag1 = null;return;}}private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e){me.Scrubbi ngEnabled = true;me.Position = TimeSpan.FromSeconds(slider1.Value);}private void MenuItem_Click(object sender, RoutedEventArgs e){OpenFileDialog ofp = new OpenFileDialog();ofp.Multi select = true;ofp.ShowDialog();if (ofp.FileName == ""){System.Windows.Forms.MessageBox.Show("请?选?择?正y确¨¡¤的Ì?文?件t");return;}for (int i = 0; i <= ofp.FileNames.Count() - 1; i++){sb.Append(ofp.FileNames[i]);sb.Append("\r\n");if (ofp.SafeFileNames[i] != ""){listBox1.Items.Add(ofp.SafeFileNames[i]);str8.Add(ofp.FileNames[i].Substring(0, ofp.FileNames[i].LastIndexOf("\\") + 1));}}FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D表À¨ª.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);bs = Encoding.Default.GetBytes(sb.ToString());fs.Write(bs, 0, bs.Length);fs.Flush();fs.Close();}private void MenuItem_Click_1(object sender, RoutedEventArgs e){try{FileStream fs1 = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D表À¨ª.txt", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);byte[] bt = new byte[fs1.Length];fs1.Read(bt, 0, bt.Length);fs1.Dispose();string str = Encoding.Default.GetString(bt);string[] s = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);List<string> list = new List<string>(s);if (listBox1.SelectedItem != null){for (int i = 0; i < s.Length - 1; i++){if (s[i].Contains(listBox1.SelectedItem.ToString())){list.RemoveAt(i);}}}s = (string[])list.ToArray();FileInfo file = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D表À¨ª.txt");file.Refresh();file.Delete();List<string> li = new List<string>();li=s.Distinct().ToList();StringBuilder sb = new StringBuilder();for (int i = 0; i <= li.Count - 1; i++){sb.Append(li[i]);sb.Append("\r\n");}FileStream fs2 = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D表À¨ª.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);bs = Encoding.Default.GetBytes(sb.ToString());fs2.Write(bs, 0, bs.Length);fs2.Flush();fs2.Close();}catch {}listBox1.Items.Remove(listBox1.SelectedItem);}private void MenuItem_Click_2(object sender, RoutedEventArgs e){me.Stop();listBox1.Items.Clear();FileInfo file = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\歌¨¨曲¨²列¢D表À¨ª.txt");file.Refresh();file.Delete();}private void me_MediaEnded(object sender, RoutedEventArgs e){if (flag1 == null){if (listBox1.SelectedIndex == listBox1.Items.Count - 1){listBox1.SelectedIndex = 0;}else{listBox1.SelectedIndex++;}musicplay();}if (flag1 == true){Random rnd = new Random();listBox1.SelectedIndex = rnd.Next(0, listBox1.Items.Count - 1);musicplay();}if (flag1 == false){musicplay();}}}}。

wpf中嵌入windowsmediaplayer

wpf中嵌入windowsmediaplayer

WPF 中嵌入Windows Media Player上一篇通过MediaElement 控件在WPF 4 中制作了简单的媒体播放器。

本篇将直接把Windows Media Player 嵌入WPF 中实现同样的效果。

起初创建该实例是基于.Net Framework 4.0 完成后编译顺利通过,但F5 时出现了问题。

提示无法加载Interop.WMPLib,调试了许久也没搞出个明堂。

最后转用.Net 3.5 问题解决,难道是4.0 不支持?感兴趣的朋友可下载代码进一步研究。

创建项目1. 新建一个基于.Net Framework 3.5 的WPF 应用程序项目:WPFWMP。

2. 在工程中新建Windows Forms Control Library 项目:WMPControlLibrary。

创建WMP 控件下面要在WMPControlLibrary 中创建Windows Media Player 控件,在项目中加入Windows Media Player COM。

在左侧工具栏中若没有Windows Media Player 控件的话,可以右键General 选择Choose Items,在COM 组件列表中勾选Windows Media Player 选项。

将Windows Media Player 控件拖入设计窗口,并将Dock 设置为Fill 填充控件。

控件效果图:F6 编译项目后会生成以下三个DLL 文件,这就是我们稍后将要在WPF 中用到的WMP 控件库。

嵌入WMP 控件回到WPF 项目在前篇文章的基础上,保留其中“Open File” 按键和Button 样式。

将上面三个DLL文件及System.Windows.Forms、WindowsFormsIntegration 加入项目。

在XAML 中加入AxWMPLib 命名空间,并将上篇MediaElement 替换为AxWindowsMediaPlayer 控件,注意此处是将WinForm 控件嵌入WPF 程序,所以要将AxWindowsMediaPlayer 控件放到&lt;WindowsFormsHost&gt;标签中。

用WPF制作简单的播放器

用WPF制作简单的播放器

用WPF制作简单的播放器3 2011-4用WPF制作简单的播放器制作这个播放器我们要用到的一个控件是MediaElement。

在WPF中有个MediaPlayer类,这个类位于System.Windows.Media 命名空间下。

(提示:由于MediaPlayer是基于Windows Media Player 10 或更高版本,因此,只要Windows Media Player能播放的视频格式(如.wmv, .avi, .mpg等),在MediaPlayer或MediaElement中都能播放(前提是系统中必须安装Windows Media Player 10 或更高)。

)首先从工具箱里面拖出一个MediaElement,拖出3个按钮分别用于播放、暂停、停止,再拖出两个Slider分别用于控制播放进度和音量大小。

最后再调整一下布局界面,如下图:注意:MediaElement 的LoadedBehavior属性必须设置为 Manual 才能以交互方式停止、暂停和播放媒体。

XAML代码:01 <Window x:Class="Player.Window1"0 2xmlns="/winfx/2006/xaml/presen tation"03 xmlns:x="/winfx/2006/xaml"04 Title="Window1" Height="269" Width="357">05 <Grid>0 6<MediaElementSource="C:\Users\Administrator\Desktop\1.wmv" Margin="0,0,0,64 " Name="mediaElement1" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="Fill" MediaOpened="mediaElement1_MediaOpened" />07 <Button Height="33" Name="Play"VerticalAlignment="Bottom" FontSize="15" FontFamily="arial" Margin="13,0,0,3" HorizontalAlignment="Left" Width="34" Click="button1_Click">?</Button>08 <Button Height="33" Margin="55,0,0,3" Name="Pause"VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="36" Click="Pause_Click">█</Button>09 <Button Height="33" Margin="100,0,0,3" Name="Stop"VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="36" Click="Stop_Click">●</Button>10 <Slider Height="27" Margin="142,0,110,2"Name="Volume" VerticalAlignment="Bottom" HorizontalContentAlignment="Left"VerticalContentAlignment="Center" Minimum="0" Maximum="1" Value="0.5" ValueChanged="ChangeMediaVolume" Width="80" />11 <Slider Height="23" Margin="0,0,0,35"Name="TimeLine" VerticalAlignment="Bottom"ValueChanged="TimeLine_ValueChanged_1" Maximum="60" />1213 </Grid>14 </Window>下面是.cs文件中的功能代码:01 using System;02 using System.Collections.Generic;03 using System.Linq;04 using System.Text;05 using System.Windows;06 using System.Windows.Controls;07 using System.Windows.Data;08 using System.Windows.Documents;09 using System.Windows.Input;10 using System.Windows.Media;11 using System.Windows.Media.Imaging;12 using System.Windows.Navigation;13 using System.Windows.Shapes;1415 namespace Player16 {17 /// <summary>18 /// Window1.xaml 的交互逻辑19 /// </summary>20 public partial class Window1 : Window21 {22 public Window1()23 {24 InitializeComponent();25 }2627 private void button1_Click(object sender,RoutedEventArgs e)28 {29 mediaElement1.Play();30 //将音量调节到我们设定的音量值0.531 InitializePropertyValues();3233 }3435 private void Pause_Click(object sender,RoutedEventArgs e)36 {37 mediaElement1.Pause();38 }3940 private void Stop_Click(object sender,RoutedEventArgs e)41 {42 mediaElement1.Stop();43 }4445 private void ChangeMediaVolume(object sender,RoutedPropertyChangedEventArgs<double> e)46 {4748 mediaElement1.Volume =(double)Volume.Value;4950 }515253 void InitializePropertyValues()54 {55 mediaElement1.Volume =(double)Volume.Value;56 }5758 private void mediaElement1_MediaOpened(objectsender, RoutedEventArgs e) 59 {60 //获取媒体的时间长度,并赋予进度条的Maxinum61 TimeLine.Maximum =mediaElement1.NaturalDuration.TimeSpan.TotalMilliseconds;62 }6364 private void TimeLine_ValueChanged_1(objectsender, RoutedPropertyChangedEventArgs<double> e) 65 {66 //获取当前进度条的Value,也就是要播放的时间位置,定位媒体的位置67 int SliderValue = (int)TimeLine.Value;68 TimeSpan ts = new TimeSpan(0, 0, 0, 0,SliderValue);69 mediaElement1.Position = ts;7071 }727374 }75 }效果如下图所示:其他就不多说了,要提一点的是这个进度条这样写还不能和媒体的进度一样前进,要实现这个功能的话可以用MediaTimeline,有时间可以试一试。

WPFMediElement实现视频播放

WPFMediElement实现视频播放

WPFMediElement实现视频播放WPF中可以使用MediaElement控件来进行音视频播放,然后需要做个进度条啥的,但是MediaElement.Position(进度)和MediaElement.NaturalDuration居然都不是依赖属性,简直不能忍!好吧,首先说说比较传统的做法(winform?)slider用来显示进度以及调整进度,tb1显示当前进度的时间值,tb2显示视频的时常。

player_Loaded 事件中使用DispatcherTimer来定时器获取当前视频的播放进度,player_MediaOpened 事件中获取当前视频的时长(只有在视频加载完成后才可以获取到)slider_ValueChanged 事件中执行对视频进度的调整1.xaml:2.<MediaElement Name="player" Source="e:\MVVMLight (1).wmv" Loaded="player_Loaded"3.MediaOpened="player_MediaOpened"/>4.<Slider Grid.Row="1" Margin="10" Name="slider" Value Changed="slider_ValueChanged"/>5.<WrapPanel Grid.Row="1" Margin="0,40,0,0">6.<TextBlock Name="tb1" Width="120"/>7.<TextBlock Name="tb2" Width="120"/>8.</WrapPanel>9.10.后台代码:11.private void player_Loaded(object sender, Routed EventArgs e)12.{13.DispatcherTimer timer = new DispatcherTimer();14.timer.Interval = TimeSpan.FromMilliseconds(1000);15.timer.Tick += (ss, ee) =>16.{17.//显示当前视频进度18.var ts = player.Position;19.tb1.Text = string.Format("{0:00}:{1:00}:{2:00}", ts.H ours, ts.Minutes, ts.Seconds);slider.Value = ts.TotalMilliseconds;20.};21.timer.Start();22.}23.24.private void player_MediaOpened(object sender, RoutedEventArgs e)25.{26.//显示视频的时长27.var ts = player.NaturalDuration.TimeSpan;28.tb2.Text = string.Format("{0:00}:{1:00}:{2:00}", ts.H ours, ts.Minutes, ts.Seconds);29.slider.Maximum = ts.TotalMilliseconds;30.}31.32.private void slider_ValueChanged(object sender, R outedPropertyChangedEventArgs<double> e)33.{34.//调整视频进度35.var ts = TimeSpan.FromMilliseconds(e.NewValue);36.player.Position = ts;37.}。

教你制作一个自己的播放器

教你制作一个自己的播放器
进入编辑状态:
3.制作:
(1)制作背景;
“背景”栏的后面是添加网址的。可以随时更换。一般用图片或FLASAH作品。注意修改后面的大小。同样修改特效,可以不要(删除网址)。标题别忘记修名称,再点下面的“删除”。添加你需要的歌曲和音乐,注意用MP3和FLV格式的。
注册成功后再点下面的这样就进入了你自己的管理中心
教你制作一个自己的播放器
教你制作一个自己的播放器
点击下面我制作的六款播放器:如果你喜欢,请按照下面步骤操作:
1.首先要在下面的网站注册(点网址):
出现:
点注册:
依次把上面填好,点“点击注册”。注册成功后,再点下面的这样就进入了你自己的管理中心。
2.点你自己的管理中心
不要忘记点上面的“保存”。
4.发表:
点看效果。点旁左边的 再点就可以复制代码成功。
在写日志里,在代码状态下粘贴并发表。OK!

C#使用WPF用MediaElement控件实现视频循环播放

C#使用WPF用MediaElement控件实现视频循环播放

C#使⽤WPF⽤MediaElement控件实现视频循环播放 在WPF⾥⽤MediaElement控件,实现⼀个循环播放单⼀视频的程序,同时可以控制视频的播放、暂停、停⽌。

⼀种⽅式,使⽤MediaElement.MediaEnded事件,在视频播放结束后,⾃动重新播放; 另⼀种⽅式,使⽤WPF定时器,在定时器事件⾥写⼊视频播放代码。

后者优点是可以控制循环时长,不必等到视频播放结束就可以开始下⼀次播放,⽐如:同时启动多个播放程序,使多个时长不同的视频同时播放,⽆限循环,如果采⽤第⼀种⽅式,累计多次⾃动播放后,视频内容就⽆法同步。

第⼀种⽅式:XAML:<MediaElement x:Name="mediaElement" HorizontalAlignment="Left" Height="261" VerticalAlignment="Top" Width="507"/><Button x:Name="btnPlay" Content="Play" HorizontalAlignment="Left" Margin="68,279,0,0" VerticalAlignment="Top" Width="75" Click="btnPlay_Click"/><Button x:Name="btnPause" Content="Pause" HorizontalAlignment="Left" Margin="170,279,0,0" VerticalAlignment="Top" Width="75" Click="btnPause_Click"/><Button x:Name="btnStop" Content="Stop" HorizontalAlignment="Left" Margin="295,279,0,0" VerticalAlignment="Top" Width="75" Click="btnStop_Click"/>C#:// 窗⼝加载事件private void Window_Loaded(object sender, RoutedEventArgs e){// 绑定视频⽂件mediaElement.Source = new Uri("D:/bird.mp4");// 交互式控制mediaElement.LoadedBehavior = MediaState.Manual;// 添加元素加载完成事件 -- ⾃动开始播放mediaElement.Loaded += new RoutedEventHandler(media_Loaded);// 添加媒体播放结束事件 -- 重新播放mediaElement.MediaEnded += new RoutedEventHandler(media_MediaEnded);// 添加元素卸载完成事件 -- 停⽌播放mediaElement.Unloaded += new RoutedEventHandler(media_Unloaded);}/*元素事件*/private void media_Loaded(object sender, RoutedEventArgs e){(sender as MediaElement).Play();}private void media_MediaEnded(object sender, RoutedEventArgs e){// MediaElement需要先停⽌播放才能再开始播放,// 否则会停在最后⼀帧不动(sender as MediaElement).Stop();(sender as MediaElement).Play();}private void media_Unloaded(object sender, RoutedEventArgs e){(sender as MediaElement).Stop();}/*播放控制按钮的点击事件*/private void btnPlay_Click(object sender, RoutedEventArgs e){mediaElement.Play();}private void btnPause_Click(object sender, RoutedEventArgs e){mediaElement.Pause();}private void btnStop_Click(object sender, RoutedEventArgs e){mediaElement.Stop();}第⼆种⽅式: 注:使⽤DispatcherTimer,需要添加System.Windows.Threading命名空间。

WPF中的视频和音频byxirihanlin幸福像花儿一样开放

WPF中的视频和音频byxirihanlin幸福像花儿一样开放

WPF中的视频和音频byxirihanlin幸福像花儿一样开放WPF中的视频——(1)WPF的视频支持也是基于MediaPlayer类,以及和它相关的MediaElement和MediaTimeline。

由于MediaPlayer是基于Windows Media Player 10 或更高版本,因此,只要Windows Media Player能播放的视频格式(如.wmv, .avi, .mpg等),在MediaPlayer或MediaElement中都能播放(前提是系统中必须安装Windows Media Player 10 或更高)。

WPF中视频的播放和音频有些相似(在用MediaElement时候),通过设置Source属性为视频文件即可。

如果使用MediaPlayer,由于视频的播放需要显示窗口,而MediaPlayer是为程序代码设计的(不参与UI显示),要显示MediaPlayer加载的媒体,必须使用VideoDrawing或DrawingContext(在(2)中再描述)。

用MediaElement播放视频的代码如下:<Grid><MediaElement Source="C:"Users"Public"Videos"Sample Videos"bear.wmv" Opacity="0.5"><MediaElement.Clip><EllipseGeometry Center="220 220" RadiusX="220" RadiusY="220"/></MediaElement.Clip><youtTransform><RotateTransform Angle="180"/></youtTransform></MediaElement><MediaElement Source="C:"Users"Public"Videos"Sample Videos"bear.wmv" Opacity="0.5"><MediaElement.Clip><EllipseGeometry Center="220 220" RadiusX="220"RadiusY="220"/></MediaElement.Clip></MediaElement></Grid>使用两个MediaElement播放同一个视频文件,其中一个做了180度旋转,显示的效果如下图所示:如果要控制视频的播放,可以与MediaTimeline搭配使用,并用PauseStoryboard、ResumeStoryboad等动作进行控制。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

namespace mykinect { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { private KinectSensorChooser sensorChooser; private System.Windows.Forms.Timer timer = new Timer() { }; string root = "", pathMedia = ""; public MainWindow() { InitializeComponent(); timer.Tick += new EventHandler(timer_Tick); timer.Enabled = true; SetPlayer(false); Loaded += OnLoaded;
try { args.OldSensor.DepthStream.Range = DepthRange.Default; args.OldSensor.SkeletonStream.EnableTrackingIn NearRange = false; args.OldSensor.DepthStream.Disable(); args.OldSensor.SkeletonStream.Disable(); } catch (InvalidOperationException) { // KinectSensor might enter an invalid state while enabling/disabling streams or stream features. // E.g.: sensor might be abruptly unplugged. error = true;
{ this.mediaElement.LoadedBehavior = MediaState.Manual; string[] files = Directory.GetFiles(pathMedia); foreach (string file in files) { fileNames.Add(file.Substring(stIndexOf( '\\') + 1)); } this.mediaElement.Source = new Uri(files[0]); this.mediaElement.Play(); } private void mediaElement1_MediaEnded(object sender, RoutedEventArgs e)
InitPath(); AddItemToListView(); } void timer_Tick(object sender, EventArgs e) { //模拟的做一些耗时的操作 this.progress.Value = this.mediaElement.Position.Ticks; } private void InitPath() { ApplicationPath ap = new ApplicationPath(); root = ap.GetRtfPath("root"); pathMedia = root + ap.GetRtfPath("pathMedia"); }
//mediaElement.Stop(); //SetPlayer(false);//我想在这里实 现暂停的功能 string fileName = this.listView1.SelectedValue.ToString(); this.mediaElement.Source = new Uri(pathMedia + "//" + fileName); //this.mediaElement.Play(); //mediaElement.Source = new Uri(openFileDialog.FileName, 0); progress.Value = 0; playBtn.IsEnabled = true; }
//将视频目录下的视频名称添加到ListView 中 private void AddItemToListView() { string[] files = Directory.GetFiles(pathMedia); foreach (string file in files) { this.listView1.Items.Add(file.Substring(file.L astIndexOf('\\') + 1)); } } //窗体加载时调用视频,进行播放 private void Window_Loaded(object sender, RoutedEventArgs e) { MediaElementControl(); } List<string> fileNames = new List<string>(); private void MediaElementControl()
{ //获取当前播放视频的名称(格式为: xxx.wmv) string path = this.mediaElement.Source.LocalPath; string currentfileName = path.Substring(stIndexOf('\\') + 1); //对比名称列表,如果相同,则播放下 一个,如果播放的是最后一个,则从第一个重新开始 播放 for (int i = 0; i < fileNames.Count; i++) { if (currentfileName == fileNames[i]) { if (i == fileNames.Count 1) { this.mediaElement.Source = new Uri(pathMedia +
private void SetPlayer(bool bVal) { stopBtn.IsEnabled = bVal; playBtn.IsEnabled = bVal;
} private void PlayerPause() { SetPlayer(true); if (playBtn.Content.ToString() == "Play") { mediaElement.Play(); playBtn.Content = "Pause"; mediaElement.ToolTip = "Click to Pause"; } else { mediaElement.Pause(); playBtn.Content = "Play"; mediaElement.ToolTip = "Click to Play"; }
"//" + fileNames[0]); this.mediaElement.Play(); } else { this.mediaElement.Source = new Uri(pathMedia + "//" + fileNames[i + 1]); this.mediaElement.Play(); } break; } } } //播放列表选择时播放对应视频 private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e) {
} } if (args.NewSensor != null) { try { args.NewSensor.DepthStream.Enable(DepthImageFo rmat.Resolution640x480Fps30); args.NewSensor.SkeletonStream.Enable(); try { args.NewSensor.DepthStream.Range = DepthRange.Near; args.NewSensor.SkeletonStream.EnableTrackingIn NearRange = true;
பைடு நூலகம்
args.NewSensor.SkeletonStream.TrackingMode = SkeletonTrackingMode.Seated; } catch (InvalidOperationException) { args.NewSensor.DepthStream.Range = DepthRange.Default; args.NewSensor.SkeletonStream.EnableTrackingIn NearRange = false; } } catch (InvalidOperationException) { error = true; } } }
private void Button_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "wmv files(*.wmv)|*.wmv|wmv files(*.avi)|*.avi"; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { System.Windows.MessageBox.Show(openFileDialog. FileName); mediaElement.Source = new Uri(openFileDialog.FileName, 0); playBtn.IsEnabled = true; } //MediaElementControl(); } private void playBtn_Click(object
相关文档
最新文档