基于Windows Media Player, 写自己的播放器【有源码,可下载整个工程】

来源:互联网 发布:神作 知乎 编辑:程序博客网 时间:2024/04/29 16:40
最近有客户问我,怎么把Windows Media Player 嵌套在自己的项目中。

以前我在Delphi下玩过Windows Media Player,可是在Microsoft Visual Studio 2008 没有测试过。

到网上搜索了一把,果然得到很多例子。

其中CSDN上有个例子写的不错,不过要扣5分,不过我用自己的分已经下载了,大家要顶啊:
附件: WindowsMediaPlayer1.rar (下载 85 次)

我这个例子就是用这个CSDN上提供的例子,是基于Microsoft Visual Studio 2005下开发的,我只是简单的把这个例子更新到Microsoft Visual Studio 2008 下,不过有点小麻烦,还好,我已经解决了。

不多说了,直接上代码,

Windows Media Player
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.IO;
  9. using System.Threading;
  10. using AxWMPLib;

  11. namespace MediaPlayer
  12. {
  13.     
  14.     public partial class Form1 : Form
  15.     {
  16.         public static Form1 form1;
  17.         public string oldPath;
  18.         //To Load all Songs specified in Default Path
  19.         public DelegateLoadSongs m_loadSongs;
  20.         public delegate void DelegateLoadSongs();
  21.         //Thread used in loading all songs in Default Path.
  22.         public Thread execloadSongs;
  23.         public ToolStripMenuItem parentItem;
  24.         //To Add individual song as a New MenuItem
  25.         public DelegateAddSong m_AddSongs;
  26.         public delegate void DelegateAddSong(string path);
  27.         public Form1()
  28.         {
  29.             InitializeComponent();
  30.         }

  31.         private void openToolStripMenuItem_Click(object sender, EventArgs e)
  32.         { 
  33.             //To Select Songs.
  34.             bool isFileExist = false;
  35.             WMPLib.IWMPPlaylistCollection playlistColl;
  36.             WMPLib.IWMPPlaylist playlist = axWindowsMediaPlayer1.newPlaylist("Test", "");
  37.             if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
  38.             {
  39.                 //If multiple Songs are selected,
  40.                 //than it will create a New Playlist and add those songs to that list and set it as Current PlayList.
  41.                 if (openFileDialog1.FileNames.Length > 1)
  42.                 {
  43.                     playlistColl = axWindowsMediaPlayer1.playlistCollection;
  44.                     playlist = playlistColl.newPlaylist("Test");
  45.                     if (recentFilesToolStripMenuItem.DropDownItems.Count == 0)
  46.                     {
  47.                         foreach (string f in openFileDialog1.FileNames)
  48.                         {
  49.                             recentFilesToolStripMenuItem.DropDownItems.Add(f, null, recentFilesMenuItem_Click);
  50.                             RecentListcontextMenuStrip.Items.Add(f, null, recentFilesMenuItem_Click);
  51.                             WMPLib.IWMPMedia media = axWindowsMediaPlayer1.newMedia(f);
  52.                             playlist.appendItem(media);
  53.                         }
  54.                     }
  55.                     else
  56.                     {
  57.                         foreach (string f in openFileDialog1.FileNames)
  58.                         {
  59.                             isFileExist = false;
  60.                             WMPLib.IWMPMedia media = axWindowsMediaPlayer1.newMedia(f);
  61.                             playlist.appendItem(media);
  62.                             //To add to Recent Play List.
  63.                             foreach (ToolStripItem item in recentFilesToolStripMenuItem.DropDownItems)
  64.                             {
  65.                                 if (item.Text == f)
  66.                                 {
  67.                                     isFileExist = true;
  68.                                     break;
  69.                                 }
  70.                             }
  71.                             //If selected Song is not Present in Recent Songs List previously,than it will add it.
  72.                             if (!isFileExist)
  73.                             {
  74.                                 recentFilesToolStripMenuItem.DropDownItems.Add(f, null, recentFilesMenuItem_Click);
  75.                                 RecentListcontextMenuStrip.Items.Add(f, null, recentFilesMenuItem_Click);
  76.                             }
  77.                         }
  78.                     }
  79.                     axWindowsMediaPlayer1.currentPlaylist = playlist;
  80.                     axWindowsMediaPlayer1.Ctlcontrols.play();
  81.                 }
  82.                     //This Will add selected song to Recent PlayList and Plays it.
  83.                 else if (openFileDialog1.FileNames.Length == 1)
  84.                 {
  85.                     axWindowsMediaPlayer1.URL = openFileDialog1.FileName;
  86.                     form1.Text = axWindowsMediaPlayer1.URL;
  87.                     if (recentFilesToolStripMenuItem.DropDownItems.Count == 0)
  88.                     {
  89.                         recentFilesToolStripMenuItem.DropDownItems.Add(openFileDialog1.FileName, null, recentFilesMenuItem_Click);
  90.                         RecentListcontextMenuStrip.Items.Add(openFileDialog1.FileName, null, recentFilesMenuItem_Click);
  91.                     }
  92.                     else
  93.                     {
  94.                         foreach (ToolStripItem item in recentFilesToolStripMenuItem.DropDownItems)
  95.                         {
  96.                             if (item.Text == openFileDialog1.FileName)
  97.                             {
  98.                                 isFileExist = true;
  99.                                 break;
  100.                             }
  101.                         }
  102.                         if (!isFileExist)
  103.                         {
  104.                             recentFilesToolStripMenuItem.DropDownItems.Add(openFileDialog1.FileName, null, recentFilesMenuItem_Click);
  105.                             RecentListcontextMenuStrip.Items.Add(openFileDialog1.FileName, null, recentFilesMenuItem_Click);
  106.                         }
  107.                     }
  108.                 }
  109.                 form1.Text = axWindowsMediaPlayer1.URL;
  110.             }
  111.         }
  112.         private void recentFilesMenuItem_Click(object sender, EventArgs e)
  113.         {
  114.             try
  115.             {
  116.                 //This Will just plays the selected song from Recent PlayList.
  117.                 bool isFileExist = false;
  118.                 if (File.Exists(((ToolStripItem)sender).Text))
  119.                 {
  120.                     axWindowsMediaPlayer1.URL = ((ToolStripItem)sender).Text;
  121.                     form1.Text = ((ToolStripItem)sender).Text;
  122.                     foreach (ToolStripItem item in recentFilesToolStripMenuItem.DropDownItems)
  123.                     {
  124.                         if (item.Text == ((ToolStripItem)sender).Text)
  125.                         {
  126.                             isFileExist = true;
  127.                             break;
  128.                         }
  129.                     }
  130.                     if (!isFileExist)
  131.                     {
  132.                         recentFilesToolStripMenuItem.DropDownItems.Add(((ToolStripItem)sender).Text, null, recentFilesMenuItem_Click);
  133.                         RecentListcontextMenuStrip.Items.Add(((ToolStripItem)sender).Text, null, recentFilesMenuItem_Click);
  134.                     }
  135.                 }
  136.             }
  137.             catch { }
  138.         }

  139.         private void playToolStripMenuItem_Click(object sender, EventArgs e)
  140.         {
  141.             //To Play the selected song.
  142.             axWindowsMediaPlayer1.Ctlcontrols.play();
  143.         }

  144.         private void pauseToolStripMenuItem_Click(object sender, EventArgs e)
  145.         {
  146.             //To pause the selected song.
  147.             axWindowsMediaPlayer1.Ctlcontrols.pause();
  148.         }

  149.         private void stopToolStripMenuItem_Click(object sender, EventArgs e)
  150.         {
  151.             //To Stop the selected song.
  152.             axWindowsMediaPlayer1.Ctlcontrols.stop();
  153.         }

  154.         private void exitToolStripMenuItem_Click(object sender, EventArgs e)
  155.         {
  156.             //To Exit Application.
  157.             Application.Exit();
  158.         }

  159.         private void topMostToolStripMenuItem_Click(object sender, EventArgs e)
  160.         {
  161.             //To Show Media Player on top of other Windows.
  162.             if (topMostToolStripMenuItem.Checked)
  163.             {
  164.                 topMostToolStripMenuItem.Checked = false;
  165.                 form1.TopMost = false;
  166.                 form1.ShowInTaskbar = true;
  167.             }
  168.             else
  169.             {
  170.                 topMostToolStripMenuItem.Checked = true;
  171.                 form1.TopMost = true;
  172.                 form1.ShowInTaskbar = false;
  173.             }
  174.         }
  175.         private void opacityToolStripMenuItem_Click(object sender, EventArgs e)
  176.         {
  177.             //To Set Opacity of the Form.
  178.             if (opacityToolStripMenuItem.Checked)
  179.             {
  180.                 opacityToolStripMenuItem.Checked = false;
  181.                 form1.Opacity = 1;
  182.             }
  183.             else
  184.             {
  185.                 opacityToolStripMenuItem.Checked = true;
  186.                 form1.Opacity = 0;
  187.             }
  188.         }
  189.         
  190.         private void showInTaToolStripMenuItem_Click(object sender, EventArgs e)
  191.         {
  192.             //To Set whether to display Form in TaskBar or not.
  193.             if (showInTaToolStripMenuItem.Checked)
  194.             {
  195.                 showInTaToolStripMenuItem.Checked = false;
  196.                 form1.ShowInTaskbar = false;
  197.             }
  198.             else
  199.             {
  200.                 showInTaToolStripMenuItem.Checked = true;
  201.                 form1.ShowInTaskbar = true;
  202.             }
  203.         }

  204.         private void axWindowsMediaPlayer1_MediaError(object sender, AxWMPLib._WMPOCXEvents_MediaErrorEvent e)
  205.         {
  206.             //Generic Error Message.
  207.             MessageBox.Show("Error occured");
  208.         }

  209.         private void showBorderToolStripMenuItem_Click(object sender, EventArgs e)
  210.         {
  211.             //To Set whether Form Border should be displayed or not.
  212.             if (showBorderToolStripMenuItem.Checked)
  213.             {
  214.                 showBorderToolStripMenuItem.Checked = false;
  215.                 form1.FormBorderStyle = FormBorderStyle.None;
  216.             }
  217.             else
  218.             {
  219.                 showBorderToolStripMenuItem.Checked = true;
  220.                 form1.FormBorderStyle = FormBorderStyle.Sizable;
  221.             }
  222.             
  223.         }
  224.         private void notifyIcon1_DoubleClick(object sender, EventArgs e)
  225.         {
  226.             //To Set Visibility of the Form.
  227.             try
  228.             {
  229.                 if (form1.Visible)
  230.                 {
  231.                     form1.Visible = false;
  232.                     form1.Opacity = 1;
  233.                 }
  234.                 else
  235.                 {
  236.                     form1.Visible = true;
  237.                 }
  238.             }
  239.             catch
  240.             { }
  241.         }

  242.         private void timer1_Tick(object sender, EventArgs e)
  243.         {
  244.             //To Change NotifyIcon Image.
  245.             try
  246.             {
  247.                 Random r = new Random();
  248.                 notifyIcon1.Icon = new Icon("..\\..\\Images\\" + r.Next(1,11) + ".ico");
  249.             }
  250.             catch { }
  251.         }

  252.         private void menuStrip1_MouseHover(object sender, EventArgs e)
  253.         {
  254.             //T Show Form Border.
  255.             form1.FormBorderStyle = FormBorderStyle.Sizable;
  256.         }

  257.         private void Form1_Load(object sender, EventArgs e)
  258.         {
  259.             //To Load Recent PlayList Items,Default songs Path from the File.
  260.             if (File.Exists(@"c:\Media PlayList\List.txt"))
  261.             {
  262.                 StreamReader reader = new StreamReader(@"c:\Media PlayList\List.txt");
  263.                 string fname = "";
  264.                 while ((fname = reader.ReadLine()) != null)
  265.                 {
  266.                     if (!fname.StartsWith("----"))
  267.                     {
  268.                         recentFilesToolStripMenuItem.DropDownItems.Add(fname, null, recentFilesMenuItem_Click);
  269.                         RecentListcontextMenuStrip.Items.Add(fname, null, recentFilesMenuItem_Click);
  270.                     }
  271.                     else
  272.                     {
  273.                         //Default Songs Path.
  274.                         DefaultPathtoolStripTextBox.Text = fname.TrimStart('-');
  275.                         //To Load all songs present in Default Songs Path.
  276.                         DefaultPathtoolStripTextBox_KeyDown(sender, null);
  277.                     }
  278.                 }
  279.                 reader.Close();
  280.             }
  281.             
  282.         }

  283.         private void Form1_FormClosed(object sender, FormClosedEventArgs e)
  284.         {
  285.             //To Save Recent PlayList Items,Default Songs Path to the file.
  286.             if (!Directory.Exists(@"c:\Media PlayList"))
  287.             {
  288.                 Directory.CreateDirectory(@"c:\Media PlayList");
  289.             }
  290.             File.Delete(@"c:\Media PlayList\List.txt");
  291.             File.Create(@"c:\Media PlayList\List.txt").Close();
  292.             System.IO.StreamWriter writer = new StreamWriter(@"c:\Media PlayList\List.txt");
  293.             foreach (ToolStripMenuItem fItem in recentFilesToolStripMenuItem.DropDownItems)
  294.             {
  295.                 writer.WriteLine(fItem.Text);
  296.             }
  297.             writer.WriteLine("----" + DefaultPathtoolStripTextBox.Text.Trim());
  298.             writer.Close();
  299.             //To Kill the thread used to load Default Path Songs.
  300.             if (execloadSongs != null)
  301.             {
  302.                 if (execloadSongs.IsAlive)
  303.                 {
  304.                     execloadSongs.Abort();
  305.                     execloadSongs = null;
  306.                 }
  307.             }
  308.         }

  309.         private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
  310.         {
  311.             //To Show Form Border.
  312.             form1.FormBorderStyle = FormBorderStyle.Sizable;
  313.         }
  314.         private void DeleteFListToolStripMenuItem_Click(object sender, EventArgs e)
  315.         {
  316.             //To Delete Recent Songs List.
  317.             recentFilesToolStripMenuItem.DropDownItems.Clear();
  318.             File.Delete(@"c:\Media PlayList\List.txt");
  319.         }

  320.         private void axWindowsMediaPlayer1_MouseUpEvent(object sender, _WMPOCXEvents_MouseUpEvent e)
  321.         {
  322.             //To Set Visibility of Form's Border,MenuStrip.
  323.             if (menuStrip1.Visible)
  324.             {
  325.                 if (!showBorderToolStripMenuItem.Checked)
  326.                 {
  327.                     menuStrip1.Visible = false;
  328.                     form1.FormBorderStyle = FormBorderStyle.None;
  329.                     axWindowsMediaPlayer1.uiMode = "None";
  330.                     axWindowsMediaPlayer1.windowlessVideo = true;
  331.                 }
  332.             }
  333.             else
  334.             {
  335.                 if (!showBorderToolStripMenuItem.Checked)
  336.                 {
  337.                     menuStrip1.Visible = true;
  338.                     form1.FormBorderStyle = FormBorderStyle.Sizable;
  339.                     axWindowsMediaPlayer1.uiMode = "full";
  340.                     axWindowsMediaPlayer1.windowlessVideo = false;
  341.                 }
  342.             }
  343.         }
  344.         private void LoadAllSongs()
  345.         {
  346.             try
  347.             {
  348.                 //To Load all songs present in Default Songs Path.
  349.                 string paths = DefaultPathtoolStripTextBox.Text.Trim();
  350.                 string[] allpaths = paths.Split(';');
  351.                 foreach (string path in allpaths)
  352.                 {
  353.                     m_AddSongs = new DelegateAddSong(this.AddSong);
  354.                     if (Directory.Exists(path))
  355.                     {
  356.                         DirectoryInfo dirinfo1 = new DirectoryInfo(Path.GetDirectoryName(path));
  357.                         Image img = Image.FromFile("..\\..\\Images\\folder.gif");
  358.                         parentItem = SongsListtoolStripMenuItem;
  359.                         form1.getDirs(dirinfo1);
  360.                         if (recursivelyToolStripMenuItem.Checked)
  361.                         {
  362.                             LoadAllSongs(SongsListtoolStripMenuItem);
  363.                         }
  364.                     }
  365.                 }
  366.             }
  367.             catch { }
  368.         }
  369.         public void getDirs(DirectoryInfo d)
  370.         {
  371.             //To Load All Directories.
  372.             DirectoryInfo[] dirs = d.GetDirectories("*.*");
  373.             getFiles(d);
  374.             foreach (DirectoryInfo dir in dirs)
  375.             {
  376.                 this.Invoke(m_AddSongs, new object[] { dir.FullName });
  377.             }
  378.         }
  379.         public void getFiles(DirectoryInfo d)
  380.         {
  381.             //To Load All Files in a Directory.
  382.             FileInfo[] files;
  383.             files = d.GetFiles("*.*");
  384.             foreach (FileInfo file in files)
  385.             {
  386.                 String fileName = file.FullName;
  387.                 this.Invoke(m_AddSongs, new object[] { file.FullName + "??" });
  388.             }
  389.         }
  390.         private void LoadAllSongs(ToolStripMenuItem item)
  391.         {
  392.             //Recursion used to load all directory's contents.
  393.             foreach (ToolStripMenuItem item1 in item.DropDownItems)
  394.             {
  395.                 if (oldPath != item1.Text)
  396.                 {
  397.                     if (item1.Image != null)
  398.                     {
  399.                         parentItem = item1;
  400.                         oldPath = item1.Text;
  401.                         form1.getDirs(new DirectoryInfo(item1.Text));
  402.                         LoadAllSongs(item1);
  403.                     }
  404.                 }
  405.             }
  406.         }
  407.         private void AddSong(string path)
  408.         {
  409.             try
  410.             {
  411.                 //To add a song to the Default songs LIst
  412.                 if (path.EndsWith("??"))
  413.                 {
  414.                     //To Add Files without any Image in it.
  415.                     parentItem.DropDownItems.Add(path.TrimEnd('?'), null, recentFilesMenuItem_Click);
  416.                 }
  417.                 else
  418.                 {
  419.                     ToolStripMenuItem item = new ToolStripMenuItem();
  420.                     Image img = Image.FromFile("..\\..\\Images\\folder.gif");
  421.                     item.Text = path.TrimEnd('?');
  422.                     item.Image = img;
  423.                     parentItem.DropDownItems.Add(item);
  424.                 }
  425.             }
  426.             catch { }
  427.         }
  428.         private void DefaultPathtoolStripTextBox_KeyDown(object sender, KeyEventArgs e)
  429.         {
  430.             //To Load all Songs,Once Default Songs Path is Changed.
  431.             if (e == null)
  432.             {
  433.                 SongsListtoolStripMenuItem.DropDownItems.Clear();
  434.                 m_loadSongs = new DelegateLoadSongs(this.LoadAllSongs);
  435.                 ThreadStart ts = new ThreadStart(this.m_loadSongs);
  436.                 execloadSongs = new Thread(ts);
  437.                 execloadSongs.Start();
  438.                 return;
  439.             }
  440.             if (e.KeyCode == Keys.Enter)
  441.             {
  442.                 SongsListtoolStripMenuItem.DropDownItems.Clear();
  443.                 m_loadSongs = new DelegateLoadSongs(this.LoadAllSongs);
  444.                 ThreadStart ts = new ThreadStart(this.m_loadSongs);
  445.                 execloadSongs = new Thread(ts);
  446.                 execloadSongs.Start();
  447.             }
  448.         }

  449.         private void recursivelyToolStripMenuItem_Click(object sender, EventArgs e)
  450.         {
  451.             //To Set whether songs should be loaded recursively in Folders or not.
  452.             if (recursivelyToolStripMenuItem.Checked)
  453.             {
  454.                 recursivelyToolStripMenuItem.Checked = false;
  455.             }
  456.             else
  457.             {
  458.                 recursivelyToolStripMenuItem.Checked = true;
  459.             }
  460.         }
  461.         private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
  462.         {
  463.             if (e.Button == MouseButtons.Middle)
  464.             {
  465.                 //To change the Player status on Click on NotifyIcon using Middle Mouse's Button.
  466.                 if (axWindowsMediaPlayer1.status != "")
  467.                 {
  468.                     if (axWindowsMediaPlayer1.status.ToLower().StartsWith("playing"))
  469.                     {
  470.                         axWindowsMediaPlayer1.Ctlcontrols.pause();
  471.                     }
  472.                     else if (axWindowsMediaPlayer1.status.ToLower().StartsWith("paused"))
  473.                     {
  474.                         axWindowsMediaPlayer1.Ctlcontrols.play();
  475.                     }
  476.                 }
  477.             }
  478.         }
  479.     }
  480. }
复制代码
下面是整个工程, 注意:在运行工程之前,需要先添加AxInterop.WMPLib.dll,Interop.MediaPlayer.dll,Interop.WMPLib.dll引用。
WindowsMediaPlayer.rar
原创粉丝点击