用WPF控件MediaElement创建简易播放器(视频区域、播放控制区域、播放列表、循环播放)

来源:互联网 发布:独生子女政策 知乎 编辑:程序博客网 时间:2024/05/21 11:17

软件概览:



区域组成:一个MediaElement控件+一个ListView控件+一个TextBlock控件+一个Slider控件+若干button控件


功能介绍:

1、视频区

       用于播放列表中的视频内容

2、控制区

      包含播放(暂停)、停止、快进、快退、音量;返回按钮为关闭此窗体

3、播放列表

      显示所要播放的视频列表,列表中的内容位于一个盘符目录中,向此目录添加视频时,启动此程序,列表将显示此目录下的所有视频,程序已设为播放列表循环播放(非单个循环)。


代码如下:

Xaml:

<Window x:Class="泗阳行政服务中心.VentureNewsWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="VentureNewsWindow" Height="1138" Width="2000" WindowStartupLocation="CenterScreen" WindowState="Maximized" WindowStyle="None" Loaded="Window_Loaded" ShowInTaskbar="False" Background="#FF2C2C31">    <Grid>        <Grid.ColumnDefinitions>            <ColumnDefinition Width="418*" />            <ColumnDefinition Width="72*" />            <ColumnDefinition Width="83*" />            <ColumnDefinition Width="72*" />            <ColumnDefinition Width="80*" />            <ColumnDefinition Width="72*" />            <ColumnDefinition Width="68*" />            <ColumnDefinition Width="73*" />            <ColumnDefinition Width="85*" />            <ColumnDefinition Width="60*" />            <ColumnDefinition Width="604*" />            <ColumnDefinition Width="18*" />            <ColumnDefinition Width="163*" />            <ColumnDefinition Width="110*" />        </Grid.ColumnDefinitions>        <Grid.RowDefinitions>            <RowDefinition Height="15*" />            <RowDefinition Height="44*" />            <RowDefinition Height="990*" />            <RowDefinition Height="7*" />            <RowDefinition Height="37*" />            <RowDefinition Height="4*" />            <RowDefinition Height="2*" />        </Grid.RowDefinitions>        <!--  Background="#FF2C2C31" Foreground="#FF9AE500" -->        <ListView Margin="1,0,0,0" Name="listView1" SelectionMode="Single" IsSynchronizedWithCurrentItem="{x:Null}" SelectionChanged="listView1_SelectionChanged" Grid.Row="2" Grid.ColumnSpan="3" Grid.Column="11" Background="#FF2C2C31" Foreground="#FF9AE500" FontSize="20" />        <Button Content="返 回" Grid.Column="11" Grid.Row="3" Margin="1,0,0,1" Name="button1" FontSize="32" Foreground="#FF9AE500" Background="{x:Null}" Grid.ColumnSpan="3" Click="button1_Click" Cursor="Hand" Grid.RowSpan="2" />        <MediaElement Volume="{Binding ElementName=volumeSlider, Path=Value}" Grid.RowSpan="3" Name="mediaElement1" Margin="0,0,5,0" MediaEnded="mediaElement1_MediaEnded" Grid.ColumnSpan="11" />        <Slider x:Name="volumeSlider" Minimum="0" Maximum="1" Value="0.5" Margin="1,11,430,12" Grid.Row="4" Grid.Column="10" />        <TextBlock Grid.Row="4" Margin="4,7,4,5" Name="textBlock1" Text="音量:" Foreground="#FF9AE500" FontSize="20" Grid.Column="9" />        <Button Background="{x:Null}" Content="播 放" Cursor="Hand" FontSize="20" Foreground="#FF9AE500" Margin="2,1,0,1" Name="button3" Grid.Row="4" Click="button3_Click_1" Grid.Column="1" />        <Button Background="{x:Null}" Content="停 止" Cursor="Hand" FontSize="20" Foreground="#FF9AE500" Margin="2,1,0,1" Name="button4" Grid.Row="4" Click="button4_Click" Grid.Column="3" />        <Button Background="{x:Null}" Content="快 进" Cursor="Hand" FontSize="20" Foreground="#FF9AE500" Margin="2,1,0,0" Name="button5" Grid.Row="4" Click="button5_Click" Grid.Column="5" />        <Button Background="{x:Null}" Content="快 退" Cursor="Hand" FontSize="20" Foreground="#FF9AE500" Margin="1,1,2,1" Name="button6" Grid.Row="4" Click="button6_Click" Grid.Column="7" />        <Button Background="{x:Null}" Content="播放列表" Cursor="Hand" FontSize="32" Foreground="#FF9AE500" Margin="0,1,1,0" Name="button2" Grid.Column="11" Grid.ColumnSpan="3" Grid.Row="1" />    </Grid></Window>



cs:

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.Shapes;using System.IO;namespace 泗阳行政服务中心{    /// <summary>    /// VentureNewsWindow.xaml 的交互逻辑    /// </summary>    public partial class VentureNewsWindow : Window    {        string root = "", pathMedia = "";        public VentureNewsWindow()        {            InitializeComponent();            InitPath();            AddItemToListView();        }        //获取视频目录        private void InitPath()        {            ApplicationPath ap = new ApplicationPath();            root = ap.GetRtfPath("root");            pathMedia = root + ap.GetRtfPath("pathMedia");        }        //将视频目录下的视频名称添加到ListView中        private void AddItemToListView()        {            string[] files = Directory.GetFiles(pathMedia);            foreach (string file in files)            {                this.listView1.Items.Add(file.Substring(file.LastIndexOf('\\') + 1));            }        }        //窗体加载时调用视频,进行播放        private void Window_Loaded(object sender, RoutedEventArgs e)        {            MediaElementControl();        }        //存储播放列表中视频的名称        List<string> fileNames = new List<string>();        private void MediaElementControl()        {            this.mediaElement1.LoadedBehavior = MediaState.Manual;                        string[] files = Directory.GetFiles(pathMedia);                        foreach(string file in files)            {                fileNames.Add(file.Substring(file.LastIndexOf('\\') + 1));            }            this.mediaElement1.Source = new Uri(files[0]);            this.mediaElement1.Play();        }        //视频播放结束事件        private void mediaElement1_MediaEnded(object sender, RoutedEventArgs e)        {            //获取当前播放视频的名称(格式为:xxx.wmv)            string path = this.mediaElement1.Source.LocalPath;            string currentfileName = path.Substring(path.LastIndexOf('\\') + 1);            //对比名称列表,如果相同,则播放下一个,如果播放的是最后一个,则从第一个重新开始播放            for (int i = 0; i < fileNames.Count;i++ )            {                if (currentfileName == fileNames[i])                {                    if (i == fileNames.Count - 1)                    {                        this.mediaElement1.Source = new Uri(pathMedia + "//" + fileNames[0]);                        this.mediaElement1.Play();                    }                    else                    {                        this.mediaElement1.Source = new Uri(pathMedia + "//" + fileNames[i + 1]);                        this.mediaElement1.Play();                    }                    break;                }            }        }        //播放列表选择时播放对应视频        private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)        {            string fileName = this.listView1.SelectedValue.ToString();            this.mediaElement1.Source = new Uri(pathMedia + "//" + fileName);            this.mediaElement1.Play();        }        //返回按钮        private void button1_Click(object sender, RoutedEventArgs e)        {            this.Close();        }        private void button3_Click(object sender, RoutedEventArgs e)        {            this.mediaElement1.Position = this.mediaElement1.Position + TimeSpan.FromSeconds(20);        }                //播放、暂停按钮        private void button3_Click_1(object sender, RoutedEventArgs e)        {            if (button3.Content.ToString() == "播 放")            {                mediaElement1.Play();                button3.Content = "暂 停";                mediaElement1.ToolTip = "Click to Pause";            }            else            {                mediaElement1.Pause();                button3.Content = "播 放";                mediaElement1.ToolTip = "Click to Play";            }        }        //停止播放视频        private void button4_Click(object sender, RoutedEventArgs e)        {            this.mediaElement1.Stop();        }        //快进        private void button5_Click(object sender, RoutedEventArgs e)        {            mediaElement1.Position = mediaElement1.Position + TimeSpan.FromSeconds(10);        }        //快退        private void button6_Click(object sender, RoutedEventArgs e)        {            mediaElement1.Position = mediaElement1.Position - TimeSpan.FromSeconds(10);        }    }}

上面的cs代码中所用的ApplicationPath类代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml;namespace 泗阳行政服务中心{    class ApplicationPath    {        private readonly static string ImagePath = Environment.CurrentDirectory + "\\image\\";        private readonly static string RtfPath = Environment.CurrentDirectory + "\\rtf\\";        XmlDocument xDoc = new XmlDocument();        public ApplicationPath()        {            xDoc.Load(getAppConfigPath());        }        public static string getImagePath()        {            return ImagePath;        }        public static string getRtfPath()        {            return RtfPath;        }        public string getAppConfigPath()        {            return Environment.CurrentDirectory + "\\App.config";        }        //获取App.config值        public string 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");                }                else                    return "";            }            catch (Exception)            {                return "";            }        }    }}

上面代码中的App.config文件位于项目的/bin/Debug下,内容格式为:

<?xml version="1.0" encoding="utf-8"?><configuration>  <appSettings>  <add key="root" value="D:\泗阳行政服务中心文档\" /><add key="pathMedia" value="平时状态\创业新闻\" />   </appSettings></configuration>



原创粉丝点击