技术开发 频道

基于WindowsMediaPlayer的音乐播放器

  【IT168技术】闲来没事自己做了一个基于WindowsMediaPlayer的迷你音乐播放器,界面如下图

基于WindowsMediaPlayer的音乐播放器
  功能简介:

  1.循环模式:顺不播放

axWMusicPlayer.settings.setMode("shuffle", false);

  全部循环

axWMusicPlayer.settings.setMode("loop", true);

   随机播放

axWMusicPlayer.settings.setMode("shuffle", true);

  2.模拟定时关机

  程序写到定时关机,具体的调用定时关机程序省略了,程序中相应地方有注解。

定时关机代码
1 private void 关机时间toolStripTextBox_KeyPress(object sender, KeyPressEventArgs e)
2  {
3       if (e.KeyChar == (char)Keys.Enter && 关机时间toolStripTextBox.Text != "")
4       {
5           try
6           {
7              DateTime time = DateTime.Parse(关机时间toolStripTextBox.Text);  
8              TimeSpan span = new TimeSpan(time.Hour, time.Minute, 0);
9              if (span.CompareTo(new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0)) == 0) //当前关机时间
10            {  
11              if (MessageBox.Show("你设定的关机时间是当前计算机时间,是否直接关机?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.OK)
12                {
13                    MynotifyIcon.Icon = Icon.ExtractAssociatedIcon(PathBase + "\\Images\\" + "ShutDown_notifyIcon.ico");
14                    //
15 //调用关机程序
16 //
17                 }
18                 else
19                 {
20                     return;
21                 }
22             }
23             if (span.CompareTo(new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0)) < 0) //过去关机时间
24            {
25                MessageBox.Show("此时间已是过去时间,设定无效", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
26                return;
27            }
28             if (span.CompareTo(new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0)) > 0) //有效关机时间
29             {
30
31                ShutDownTime = 关机时间toolStripTextBox.Text;
32                MessageBox.Show("成功设置定时关机,计算机将于“" + ShutDownTime + "”关机…… *︶︵︶*", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
33                this.关机时间toolStripTextBox.Visible = false;
34                this.取消定时关机QToolStripMenuItem.Visible = true;
35
36                //
37 //调用关机程序
38 //
39             }
40       }
41       catch
42      {
43        MessageBox.Show("日期格式不正确,请重新输入。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
44        return;
45       }
46     }
47    if (e.KeyChar == (char)Keys.Enter && 关机时间toolStripTextBox.Text == "")
48    {
49        关机时间toolStripTextBox.Visible = false;
50    }
51  }

          3.歌曲列表信息保存在XML文件中

添加歌曲保存代码
1 private void btnList_Click(object sender, EventArgs e) //添加歌曲
2  {
3      openFileDialog1.Title = "添加歌曲";
4      openFileDialog1.FileName = "";
5      openFileDialog1.Multiselect = true;
6      openFileDialog1.Filter = "Mp3文件|*.mp3|Wav文件|*.wav|Wma文件|*.wma|Wmv文件|*.wmv|所有格式|*.*";
7     openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
8     try
9     {
10     if (openFileDialog1.ShowDialog() == DialogResult.OK)
11     {
12        //IsCreateXmlFile();
13        XmlDocument xmldoc = new XmlDocument();
14        xmldoc.Load(xmlfile);
15        XmlNode root = xmldoc.SelectSingleNode("MusicList");
16        string[] FileNamesList = openFileDialog1.FileNames;
17        foreach (string file in FileNamesList)
18        {
19            string filename= Path.GetFileName(file).Substring(0,Path.GetFileName(file).LastIndexOf('.'));
20            axWMusicPlayer.currentPlaylist.appendItem(axWMusicPlayer.newMedia(file));
21             XmlElement newelement = xmldoc.CreateElement("MusicProperty");
22             newelement.SetAttribute("MusicUrl", file);
23             newelement.SetAttribute("MusicName", filename);
24             newelement.SetAttribute("LikeCount", "0");
25             root.AppendChild(newelement);
26             Application.DoEvents();
27         }
28             xmldoc.Save(xmlfile);
29       }
30     }
31     catch(Exception ex)
32    {
33         MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
34     }
35  }

  4.主界面上的喜爱按钮实现的是歌曲排列顺序

     在下次启动程序后,程序会自动将喜爱点击次数多的歌曲排到前面

喜爱按钮事件
1 private void btnFavorite_Click(object sender, EventArgs e) //喜爱
2         {
3             if (axWMusicPlayer.currentMedia != null)
4             {
5                 XmlDocument doc = new XmlDocument();
6                 doc.Load(xmlfile);
7                 XmlNodeList nodelist = doc.SelectSingleNode("MusicList").ChildNodes;
8                 foreach (XmlNode node in nodelist)
9                 {
10                     XmlElement element = (XmlElement)node; //将XmlNode节点node转化成XmlElement型的node
11                     if (element.GetAttribute("MusicUrl") == axWMusicPlayer.currentMedia.sourceURL)
12                     {
13                         int likecount = Convert.ToInt32(element.GetAttribute("LikeCount")) + 1;
14                         element.SetAttribute("LikeCount", likecount.ToString());
15                     }
16                 }
17                 doc.Save(xmlfile);
18             }
19         }

         5、点击进度条歌曲直接跳到当前位置继续播放

    设置当前播放位置

private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
        {
            
if (e.Button == MouseButtons.Left)
            {
                axWMusicPlayer.Ctlcontrols.currentPosition
= e.X * axWMusicPlayer.currentMedia.duration / 170;
            }
        }

            注解:170为进度条总长度

  6.进度条采用自定义控件 

自定义进度条控件代码
1 /// <summary>
2 /// 迷你音乐播放器
3 /// <author>
4 ///<name>漓江烟雨</name>  
5 ///<QQ>648445213</QQ>
6 ///<date>2011.12.3</date>
7 /// </author>  
8 /// </summary>
9
10
11 namespace UCCurrentTime
12 {
13     public partial class UserControl1 : UserControl
14     {
15         /// <summary>
16 /// 设置或获取当前播放进度条的宽度
17 /// </summary>
18         public int UCTime
19         {
20             get { return this.Width; }
21             set
22             {
23                 if (this.Width >= 16)
24                 {
25                     this.Width = value;
26                 }
27                 else
28                 {
29                     this.Width = value + 16;
30                 }
31                
32             }
33         }
34
35         /// <summary>
36 /// 设置或获取当前播放进度条左边背景图片
37 /// </summary>
38         public Image LeftBackImage
39         {
40             get { return picBoxLeft.BackgroundImage; }
41             set { picBoxLeft.BackgroundImage = value; }
42         }
43
44         /// <summary>
45 /// 设置或获取当前播放进度条右边背景图片
46 /// </summary>
47         public Image RightBackImage  
48         {
49             get { return picBoxRight.BackgroundImage; }
50             set { picBoxRight.BackgroundImage = value; }
51         }
52
53         /// <summary>
54 /// 设置或获取当前播放进度条中间背景图片
55 /// </summary>
56         public Image MiddleBackImage
57         {
58             get { return picBoxMiddle.BackgroundImage; }
59             set { picBoxMiddle.BackgroundImage = value; }
60         }
61         public UserControl1()
62         {
63             InitializeComponent();
64
65             picBoxLeft.Size = new Size(8, 10);  //左边
66             picBoxRight.Size = new Size(8, 10); //右边
67             picBoxMiddle.Size = new Size(0, 10); //中间
68
69             picBoxLeft.Dock = DockStyle.Left;
70             picBoxRight.Dock = DockStyle.Right;
71             picBoxMiddle.Width = this.Width - 16;
72             picBoxMiddle.Location = new Point(8, 0);
73
74             this.BackColor = Color.Transparent;
75             picBoxLeft.BackColor = Color.Transparent;
76             picBoxRight.BackColor = Color.Transparent;
77             picBoxMiddle.BackColor = Color.Transparent;
78
79             picBoxLeft.BackgroundImage = LeftBackImage;
80             picBoxRight.BackgroundImage = RightBackImage;
81             picBoxMiddle.BackgroundImage = MiddleBackImage;
82         }
83
84         private void UserControl1_SizeChanged(object sender, EventArgs e)
85         {
86             this.Size = new Size(UCTime, 10);
87             picBoxMiddle.Width = this.Width - 16;
88         }
89     }
90 }

  timer_tick事件

timer_tick事件代码
1 private void timer1_Tick(object sender, EventArgs e)
2         {
3             try
4             {
5                 if (axWMusicPlayer.currentMedia != null)
6                 {
7                     if (axWMusicPlayer.currentMedia.name.Length > 9)
8                     {
9                         lblMusicName.Text = axWMusicPlayer.currentMedia.name.Substring(0, 9) + "...";
10                     }
11                     else
12                     {
13                        lblMusicName.Text = axWMusicPlayer.currentMedia.name;
14                     }
15                     lblcurrenttime.Text = axWMusicPlayer.Ctlcontrols.currentPositionString + " / " + axWMusicPlayer.currentMedia.durationString;
16                     UCcurrenttime = Convert.ToInt32(axWMusicPlayer.Ctlcontrols.currentPosition / axWMusicPlayer.currentMedia.duration * 170);
17                     if (UCcurrenttime <= 16)
18                     {
19                         UCcurrenttime = 16;
20                     }
21                     this.userControl11.Width = UCcurrenttime;
22                 }
23             }
24             catch
25             {
26                 return;
27             }
28         }

  this.userControl11.Width = UCcurrenttime; 设置进度条长度

  7.由于去掉了默认的标题框所以自己添加了鼠标拖动事件

鼠标拖动窗体代码
private void MiniMusicPlayer_MouseDown(object sender, MouseEventArgs e)
        {
            
if (e.Button == MouseButtons.Left)
            {
                FormPositioX
= e.X;
                FormPositioY
= e.Y;
            }
        }
        
private void MiniMusicPlayer_MouseMove(object sender, MouseEventArgs e)
        {
            
if (e.Button == MouseButtons.Left)
            {
                this.Left
+= e.X - FormPositioX;
                this.Top
+= e.Y - FormPositioY;
            }
        }

  8.检测窗体位置,超出了屏幕范围会自动靠边

处理窗体被拖动到屏幕外
1 private void MiniMusicPlayer_MouseUp(object sender, MouseEventArgs e)
2         {
3             if (this.Left <= 0)
4             {
5                 this.Left = 0;
6             }
7             if (this.Top <= 0)
8             {
9                 this.Top = 0;
10             }
11
12             int ScreenEidth = Screen.GetWorkingArea(this).Width; //获得屏幕的宽
13             int ScreenGeight = Screen.GetWorkingArea(this).Height; //获得屏幕的高
14             if (this.Left + this.Width >= ScreenEidth)
15             {
16                 this.Left = ScreenEidth - this.Width;
17             }
18             if (this.Top + this.Height >= ScreenGeight)
19             {
20                 this.Top = ScreenGeight - this.Height;
21             }
22         }

  9.组合键控制音量,默认音量为70

控制音量代码
1 private void MiniMusicPlayer_KeyDown(object sender, KeyEventArgs e) //接收组合键调节音量
2         {
3             if ((e.Control) && (e.Alt) && (e.KeyCode == Keys.Up))
4             {
5                 if (axWMusicPlayer.settings.volume >= 100)
6                 {
7                     axWMusicPlayer.settings.volume = 100;
8                 }
9                 else
10                 {
11                     axWMusicPlayer.settings.volume += 5;
12                 }
13             }
14             if (e.Control && e.Alt && (e.KeyCode == Keys.Down))
15             {
16                 if (axWMusicPlayer.settings.volume <= 0)
17                 {
18                     axWMusicPlayer.settings.volume = 0;
19                 }
20                 else
21                 {
22                     axWMusicPlayer.settings.volume -= 5;
23                 }
24             }
25         }

  10.跟据点击喜爱次数填充播放列表

按喜爱次数自动填充播放列表
1 /// <summary>
2 ///  填充播放列表
3 /// </summary>
4         protected void FillCurrenrList()
5         {
6             XmlDocument doc = new XmlDocument();
7             doc.Load(xmlfile);
8             if (doc.SelectSingleNode("MusicList").ChildNodes.Count != 0)
9             {
10                 XmlNodeList NodeList = doc.SelectSingleNode("MusicList").ChildNodes;
11                 string[] musiclist = new string[doc.SelectSingleNode("MusicList").ChildNodes.Count]; //每条MusicProperty组成一维数组
12                 int num = 0;
13                 foreach (XmlNode node in NodeList)
14                 {
15                     XmlElement element = (XmlElement)node;
16                     musiclist[num] = element.GetAttribute("MusicUrl") + ";" + element.GetAttribute("LikeCount");
17                     num++;
18                 }
19
20                 string[,] musiclist2 = new string[num, 2]; //将一维数组分割为二维数组:MusicUrl、LikeCount
21                 for (int i = 0; i < num; i++)
22                 {
23                     string[] hh = musiclist[i].Split(';');
24                     musiclist2[i, 0] = hh[0];
25                     musiclist2[i, 1] = hh[1];
26                 }
27
28                 string temp;
29                 for (int i = 0; i < num - 1; i++) //按点击次数冒泡排序,排序后的数组添加到axWMusicPlayer.currentPlaylist
30                 {
31                     for (int j = 0; j < num - 1 - i; j++)
32                     {
33                         if (Convert.ToInt32(musiclist2[j, 1]) < Convert.ToInt32(musiclist2[j + 1, 1]))
34                         {
35                             temp = musiclist2[j, 1];
36                             musiclist2[j, 1] = musiclist2[j + 1, 1];
37                             musiclist2[j + 1, 1] = temp;
38
39                             temp = musiclist2[j, 0];
40                             musiclist2[j, 0] = musiclist2[j + 1, 0];
41                             musiclist2[j + 1, 0] = temp;
42                         }
43                     }
44                 }
45
46                 for (int i = 0; i < num; i++) //填充播放列表47                 {
48                     axWMusicPlayer.currentPlaylist.appendItem(axWMusicPlayer.newMedia(musiclist2[i, 0]));  
49                 }
50             }
51         }

  帮助窗口中的一些说明:

基于WindowsMediaPlayer的音乐播放器

       源代码下载地址

0
相关文章