C# WindowsMediaPlayer 播放器

using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.Win32;
/* 工具箱 --> 右键单击选择项 --> COM 组件 --> Windows Media Player
   添加引用 --> COM --> Windows Media Player wmp.dll */

namespace WindowsMedia
{
    public partial class FormWMP : Form
    {
        #region
        private Timer timerInfo;
        private NotifyIcon notifyInfo;
        private ChineseLunisolarCalendar lunarCalendar;
        #endregion

        public FormWMP()
        {
            #region
            InitializeComponent();
            lunarCalendar = new ChineseLunisolarCalendar();
            this.AllowDrop = true; // 启用拖放。
            this.DesktopBounds = Screen.GetWorkingArea(this);
            using (RegistryKey userKey = Application.UserAppDataRegistry)
            {
                string dirPath = userKey.GetValue("URL") as string;
                if (Directory.Exists(dirPath))
                    Environment.CurrentDirectory = dirPath;
                LoadFiles();
            }
            TimerStyle();
            WMPlayerStyle();
            DrawListView();
            DrawComboBox();
            NotifyIconStyle();
            #endregion
        }

        #region NotifyIcon
        private void NotifyIconStyle()
        {
            notifyInfo = new NotifyIcon();
            notifyInfo.Visible = true;
            notifyInfo.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
            notifyInfo.Text = AppDomain.CurrentDomain.FriendlyName;
            notifyInfo.BalloonTipClosed += new EventHandler(notifyInfo_BalloonTipClosed);
            notifyInfo.MouseClick += new MouseEventHandler(notifyInfo_MouseClick);
        }

        private void notifyInfo_MouseClick(object sender, MouseEventArgs e)
        {
            switch (e.Button)
            {
                case MouseButtons.Left:
                    if (this.Visible = !this.Visible)
                        this.Activate();
                    break;
                case MouseButtons.Right:
                    notifyInfo.ShowBalloonTip(10, notifyInfo.Text, "    在系统托盘中运行", ToolTipIcon.Info);
                    break;
            }
        }

        private void notifyInfo_BalloonTipClosed(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion

        #region Timer
        private void TimerStyle()
        {
            timerInfo = new Timer();
            timerInfo.Enabled = true;
            timerInfo.Interval = 1000;
            timerInfo.Tick += new EventHandler(this.timerWMP_Tick);
        }

        private void timerWMP_Tick(object sender, EventArgs e)
        {
            switch (axWMPlayer.playState)
            {
                case WMPLib.WMPPlayState.wmppsTransitioning:
                case WMPLib.WMPPlayState.wmppsPlaying:
                    if (!toolComboBoxColor.DroppedDown)
                        listViewWMP.Focus();
                    break;
                case WMPLib.WMPPlayState.wmppsReady:
                    axWMPlayer.Ctlcontrols.play();
                    break;
            }
            Application.CurrentCulture.ClearCachedData();
            DateTime solar = DateTime.Now;
            int month = lunarCalendar.GetMonth(solar);
            int leapMonth = lunarCalendar.GetLeapMonth(lunarCalendar.GetYear(solar));
            if (0 < leapMonth && leapMonth <= month)
                --month;
            statusLabelTime.Text = string.Format("{0:F} [{1} {2:00}]", solar, DateTimeFormatInfo.CurrentInfo.MonthNames[month - 1], lunarCalendar.GetDayOfMonth(solar));
        }
        #endregion

        #region WMPlayerStyle
        private void WMPlayerStyle()
        {
            axWMPlayer.enableContextMenu = true; // 启用上下文菜单。
            axWMPlayer.stretchToFit = true; // 自动缩放。
            axWMPlayer.settings.volume = 100; // 音量调最大。
            axWMPlayer.settings.setMode("loop", true); // 循环播放。
            axWMPlayer.CurrentItemChange += new AxWMPLib._WMPOCXEvents_CurrentItemChangeEventHandler(axWMPlayer_CurrentItemChange);
        }

        private void axWMPlayer_CurrentItemChange(object sender, AxWMPLib._WMPOCXEvents_CurrentItemChangeEvent e)
        {
            if (listViewWMP.Items.Count != axWMPlayer.currentPlaylist.count)
            {
                listViewWMP.Items.Clear();
                return;
            }
            for (int index = 0; index < axWMPlayer.currentPlaylist.count; ++index)
            {
                if (axWMPlayer.currentMedia.get_isIdentical(axWMPlayer.currentPlaylist.get_Item(index)))
                {
                    ListViewItem item = listViewWMP.Items[index];
                    this.Text = item.Text;
                    item.Focused = true;
                    item.EnsureVisible();
                    break;
                }
            }
        }

        private void toolButtonBalance_Click(object sender, EventArgs e)
        {
            switch ((sender as ToolStripButton).Name)
            {
                case "toolButtonLeft":
                    axWMPlayer.settings.balance = -100; // 左声道。
                    break;
                case "toolButtonStereo":
                    axWMPlayer.settings.balance = 0; // 立体声。
                    break;
                case "toolButtonRight":
                    axWMPlayer.settings.balance = 100; // 右声道。
                    break;
            }
        }
        #endregion

        #region DrawComboBox
        private void DrawComboBox()
        {
            toolComboBoxColor.BeginUpdate();
            foreach (KnownColor kc in Enum.GetValues(typeof(KnownColor)))
            {
                Color bc = Color.FromKnownColor(kc);
                if (!bc.IsSystemColor && bc != Color.Transparent)
                    toolComboBoxColor.Items.Add(bc);
            }
            toolComboBoxColor.EndUpdate();
            toolComboBoxColor.SelectedItem = Color.BlueViolet;
            toolComboBoxColor.DropDownStyle = ComboBoxStyle.DropDownList;
            toolComboBoxColor.ComboBox.DrawMode = DrawMode.OwnerDrawFixed; // 用代码绘制控件中的所有元素,并且元素大小都相等。
            toolComboBoxColor.ComboBox.DrawItem += new DrawItemEventHandler(toolComboBoxColor_DrawItem);
        }

        private void toolComboBoxColor_DrawItem(object sender, DrawItemEventArgs e)
        {
            using (Graphics g = e.Graphics)
            using (SolidBrush b = new SolidBrush(e.BackColor))
            {
                if ((e.State & DrawItemState.Selected) != 0) // 取交集。
                    b.Color = Color.BlueViolet;
                Rectangle r = e.Bounds;
                g.FillRectangle(b, r);
                r.Offset(1, 1);
                r.Width = 52;
                r.Height -= 2;
                b.Color = Color.Black;
                g.FillRectangle(b, r);
                r.Offset(1, 1);
                r.Width -= 2;
                r.Height -= 2;
                b.Color = (Color)toolComboBoxColor.Items[e.Index];
                g.FillRectangle(b, r);
                string colorName = b.Color.Name;
                b.Color = e.ForeColor;
                g.DrawString(colorName, e.Font, b, r.X + 72, r.Y);
            }
        }
        #endregion

        #region DrawListView
        private void DrawListView()
        {
            listViewWMP.GridLines = true; // 显示网格线。
            listViewWMP.OwnerDraw = true; // 代码绘制。
            listViewWMP.MultiSelect = false; // 仅选择单项。
            listViewWMP.ShowItemToolTips = true; // 显示工具提示。
            listViewWMP.Sorting = SortOrder.None; // 禁止排序。
            listViewWMP.View = View.Details; // 详细信息。
            columnHeaderWMP.Width = listViewWMP.ClientSize.Width;
            listViewWMP.DrawColumnHeader += new DrawListViewColumnHeaderEventHandler(listViewWMP_DrawColumnHeader);
            listViewWMP.DrawItem += new DrawListViewItemEventHandler(listViewWMP_DrawItem);
            listViewWMP.ClientSizeChanged += new EventHandler(listViewWMP_ClientSizeChanged);
            listViewWMP.Click += new EventHandler(listViewWMP_Click);
            listViewWMP.KeyUp += new KeyEventHandler(listViewWMP_KeyUp);
        }

        private void listViewWMP_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
        {
            e.Graphics.FillRectangle(SystemBrushes.InactiveCaptionText, e.Bounds);
            e.DrawText(TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
        }

        private void listViewWMP_DrawItem(object sender, DrawListViewItemEventArgs e)
        {
            if ((e.State & ListViewItemStates.Focused) != 0)
                using (SolidBrush sb = new SolidBrush((Color)toolComboBoxColor.SelectedItem))
                {
                    e.Graphics.FillRectangle(sb, e.Bounds);
                }
            e.DrawText(TextFormatFlags.Default);
        }

        private void listViewWMP_ClientSizeChanged(object sender, EventArgs e)
        {
            columnHeaderWMP.Width = listViewWMP.ClientSize.Width;
        }

        private void listViewWMP_Click(object sender, EventArgs e)
        {
            if (listViewWMP.FocusedItem != null)
                axWMPlayer.Ctlcontrols.playItem(axWMPlayer.currentPlaylist.get_Item(listViewWMP.FocusedItem.Index));
        }

        private void listViewWMP_KeyUp(object sender, KeyEventArgs e)
        {
            if (listViewWMP.FocusedItem == null)
                return;
            switch (e.KeyData)
            {
                case Keys.Enter:
                    axWMPlayer.Ctlcontrols.playItem(axWMPlayer.currentPlaylist.get_Item(listViewWMP.FocusedItem.Index));
                    break;
                case Keys.Escape:
                    axWMPlayer.Ctlcontrols.stop();
                    break;
                case Keys.Space:
                    switch (axWMPlayer.playState)
                    {
                        case WMPLib.WMPPlayState.wmppsPlaying:
                            axWMPlayer.Ctlcontrols.pause();
                            break;
                        case WMPLib.WMPPlayState.wmppsPaused:
                            axWMPlayer.Ctlcontrols.play();
                            break;
                    }
                    break;
                case Keys.Left:
                    axWMPlayer.Ctlcontrols.previous();
                    break;
                case Keys.Right:
                    axWMPlayer.Ctlcontrols.next();
                    break;
                case Keys.Control | Keys.Left:
                    axWMPlayer.Ctlcontrols.currentPosition -= 5;
                    break;
                case Keys.Control | Keys.Right:
                    axWMPlayer.Ctlcontrols.currentPosition += 5;
                    break;
            }
        }
        #endregion

        #region LoadFiles
        private void toolButtonOpen_Click(object sender, EventArgs e)
        {
            if (folderBrowserWMP.ShowDialog(this) == DialogResult.OK)
            {
                Environment.CurrentDirectory = folderBrowserWMP.SelectedPath;
                LoadFiles();
            }
        }

        private void LoadFiles()
        {
            axWMPlayer.currentPlaylist.clear();
            listViewWMP.Items.Clear();
            listViewWMP.BeginUpdate();
            folderBrowserWMP.Description = Environment.CurrentDirectory;
            DirectoryInfo dir = new DirectoryInfo(Environment.CurrentDirectory);
            foreach (FileInfo info in dir.GetFiles())
            {
                if (Regex.IsMatch(info.Extension, @".(wma|mp3|swf|wmv|avi)", RegexOptions.IgnoreCase))
                {
                    WMPLib.IWMPMedia wmp = axWMPlayer.newMedia(info.FullName);
                    axWMPlayer.currentPlaylist.appendItem(wmp);
                    ListViewItem item = listViewWMP.Items.Add(Path.GetFileNameWithoutExtension(info.Name));
                    item.ToolTipText = string.Format("艺术家: {0}\n时长: {1}\n大小: {2:#,##0.00} MB", wmp.getItemInfo("Author"), wmp.durationString, info.Length / 1048576M);
                }
            }
            listViewWMP.EndUpdate();
        }

        protected override void OnDragEnter(DragEventArgs e)
        {
            base.OnDragEnter(e);
            DataObject data = e.Data as DataObject;
            if (data.ContainsFileDropList())
            {
                string dirPath = data.GetFileDropList()[0];
                if ((File.GetAttributes(dirPath) & FileAttributes.Directory) != 0)
                {
                    Environment.CurrentDirectory = dirPath;
                    LoadFiles();
                    this.Activate();
                }
            }
        }
        #endregion

        #region FormClosing
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            switch (e.CloseReason)
            {
                case CloseReason.ApplicationExitCall:
                case CloseReason.TaskManagerClosing:
                    axWMPlayer.close();
                    notifyInfo.Visible = false;
                    using (RegistryKey subKey = Application.UserAppDataRegistry)
                    {
                        subKey.SetValue("URL", Environment.CurrentDirectory);
                    }
                    break;
                case CloseReason.UserClosing:
                    this.Visible = false;
                    e.Cancel = true;
                    break;
            }
        }
        #endregion

        #region ToolStripButton
        private void toolButtonSplit_Click(object sender, EventArgs e)
        {
            splitContainerWMP.Panel1Collapsed = !splitContainerWMP.Panel1Collapsed;
        }

        private void toolButtonTopMost_Click(object sender, EventArgs e)
        {
            this.TopMost = !this.TopMost;
            toolButtonTopMost.Checked = this.TopMost;
        }

        private void toolButtonProperty_Click(object sender, EventArgs e)
        {
            if (axWMPlayer.HasPropertyPages())
                axWMPlayer.ShowPropertyPages();
        }

        private void toolButtonVideo_Click(object sender, EventArgs e)
        {
            splitContainerWMP.Panel1Collapsed = true;
            using (FormXML xml = new FormXML())
            {
                xml.Tag = axWMPlayer;
                xml.ShowDialog(this);
            }
        }
        #endregion
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个用C#实现的简单音乐播放器: ```csharp using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using WMPLib; namespace MusicPlayer { public partial class Form1 : Form { // 创建Windows Media Player对象 private WindowsMediaPlayer player; public Form1() { InitializeComponent(); // 初始化Windows Media Player player = new WindowsMediaPlayer(); // 设置播放器属性 player.settings.autoStart = false; player.settings.volume = 50; player.PlayStateChange += new _WMPOCXEvents_PlayStateChangeEventHandler(player_PlayStateChange); // 加载音乐列表 LoadMusicList(); } // 加载音乐列表 private void LoadMusicList() { // 清空原有列表 listBox1.Items.Clear(); // 获取音乐文件夹路径 string path = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // 遍历音乐文件夹下的所有音乐文件 foreach (string file in Directory.GetFiles(path, "*.mp3")) { // 添加到列表中 listBox1.Items.Add(Path.GetFileName(file)); } } // 播放音乐 private void PlayMusic(string path) { // 设置播放器的URL player.URL = path; // 开始播放 player.controls.play(); // 更新状态栏 toolStripStatusLabel1.Text = "正在播放:" + Path.GetFileName(path); } // 播放按钮的点击事件 private void button1_Click(object sender, EventArgs e) { if (listBox1.SelectedIndex >= 0) { // 获取选中项的完整路径 string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), listBox1.SelectedItem.ToString()); // 播放音乐 PlayMusic(path); } } // 暂停按钮的点击事件 private void button2_Click(object sender, EventArgs e) { player.controls.pause(); } // 停止按钮的点击事件 private void button3_Click(object sender, EventArgs e) { player.controls.stop(); } // 列表框的选中项改变事件 private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { // 如果没有选中项,则禁用播放按钮 if (listBox1.SelectedIndex < 0) { button1.Enabled = false; } else { button1.Enabled = true; } } // 播放状态改变事件 private void player_PlayStateChange(int NewState) { // 如果播放完毕,则更新状态栏 if ((WMPPlayState)NewState == WMPPlayState.wmppsMediaEnded) { toolStripStatusLabel1.Text = "播放完毕"; } } } } ``` 这个程序使用了Windows Media Player对象来实现音乐的播放、暂停和停止功能。它还可以从Windows音乐文件夹中自动加载所有MP3文件,并将它们添加到列表框中。当用户选择一个文件并点击“播放”按钮时,程序将使用Windows Media Player对象播放选定的音乐文件。程序还会更新状态栏以显示当前播放的音乐文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值