设计页面:
在这里插入图片描述
源码:

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 System.Media;
using System.Drawing.Drawing2D;

namespace _06音乐播放器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string paths = "../../img";
        string[] roadList;
        List<string> listSong = new List<string>();
        //按钮
        Bitmap Start = new Bitmap(20, 20);
        Bitmap Pause = new Bitmap(20, 20);
        Bitmap UpSong = new Bitmap(20, 20);
        Bitmap NextSong = new Bitmap(20, 20);
        SoundPlayer sound = new SoundPlayer();
        List<string> musicList = new List<string>();//装所有音乐名称
        List<string> musicPath = new List<string>();//装所有音乐路劲
        string musicString = "未找到对应歌词!";
        List<string> musicChar = new List<string>();
        List<float> musicTime = new List<float>();
        /// <summary>
        /// 加载音乐
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog()==DialogResult.OK)
            {
                roadList = openFileDialog1.FileNames;
                for (int i=0;i<roadList.Length;i++)
                {
                    listSong.Add(roadList[i]);
                    FileInfo info = new FileInfo(roadList[i]);
                    bool b = false;
                    if (musicList.Count>0)
                    {
                        b = musicList.Contains(info.Name);
                    }
                    if (b==false)
                    {
                        musicList.Add(info.Name);
                        listBox1.Items.Add(info.Name);
                        musicPath.Add(info.FullName);
                    }
                }
                foreach (var item in roadList)
                {
                    axWindowsMediaPlayer1.currentPlaylist.appendItem(axWindowsMediaPlayer1.newMedia(item));
                }
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //音乐播放时画默认音量
            graphics2 = panel2.CreateGraphics();
            axWindowsMediaPlayer1.settings.volume = 50;//设置播放时的默认音量
            graphics2.FillRectangle(Brushes.Cyan, new RectangleF(0, 0, panel2.Width * 0.5f, panel2.Height));//绘制默认音量
            //筛选器:"(*.jpg,*.png,*.jpeg,*.bmp,*.gif)|*.jpg;*.png;*.jpeg;*.bmp;*.gif|All files(*.*)|*.*;
            //括号中的内容是筛选器上的选项文字,|后面的是要选择的文件类型
            openFileDialog1.Filter = "(请选择音乐)|*.wav;*.mp3";
            DirectoryInfo directory = new DirectoryInfo(paths);
            FileInfo[] imgInfo = directory.GetFiles();
            foreach (var item in imgInfo)
            {
                string kuo = item.Extension;
                if (kuo==".jpg"||kuo==".png")
                {
                    bgList.Add(item.Name);
                }
            }
            pictureBox2.Image = Start;
            //int curents = axWindowsMediaPlayer1.settings.volume;
            //graphics2 = panel2.CreateGraphics();
            //float current = (float)curents /(float)100;
            //graphics2.FillRectangle(Brushes.Cyan, new RectangleF(0, 0, panel2.Width*current, panel2.Height));
        }
        /// <summary>
        /// 记录当前播放音乐的索引
        /// </summary>
        int currentindex = 0;
        /// <summary>
        /// 双击播放音乐
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {

            object o = listBox1.SelectedItem;

            //axWindowsMediaPlayer1.uiMode = "Invisible";//设置播放模式;Mini只有播放的暂停键和声音大小控制;None界面没有按钮只有一个黑板板;Invisible啥都不起作用只有音乐声音.
            //axWindowsMediaPlayer1.enableContextMenu = true;//设置是否启用右键菜单
            //axWindowsMediaPlayer1.fullScreen = false ;设置是否全屏显示

            //axWindowsMediaPlayer1.Ctlcontrols.pause();//暂停
            //axWindowsMediaPlayer1.Ctlcontrols.stop();//停止
            //axWindowsMediaPlayer1.Ctlcontrols.currentPosition = 1.2;//当前进度
            //string s=  axWindowsMediaPlayer1.Ctlcontrols.currentPositionString//获取当前进度字符串格式如"00:45";
            //axWindowsMediaPlayer1.Ctlcontrols.fastForward();//快进
            //axWindowsMediaPlayer1.Ctlcontrols.fastReverse();//快退
            //axWindowsMediaPlayer1.Ctlcontrols.next();
            //axWindowsMediaPlayer1.Ctlcontrols.previous();
            //axWindowsMediaPlayer1.settings.volume = 0 - 100;//音量
            //axWindowsMediaPlayer1.settings.playCount = 2;//设置播放次数
            //axWindowsMediaPlayer1.settings.autoStart = false;//是否自动播放
            //axWindowsMediaPlayer1.settings.mute = true;//是否静音
            //double s = axWindowsMediaPlayer1.currentMedia.duration;//获取媒体总长度
            //string t = axWindowsMediaPlayer1.currentMedia.durationString;获取媒体总长度如"03:45";
            // axWindowsMediaPlayer1.currentMedia.getItemInfo("Title");//title--媒体标题;author--艺术家;copyright--版权信息;description--媒体内容描述;duration--持续时间(秒);filesize--文件大小;filetype--文件类型;sourceURL--原始地址

            currentindex = musicList.IndexOf(o.ToString());
            PlayMusic(musicPath[currentindex]);
           
            pictureBox2.Image = Pause;

        }
        //渐变
        //private void buttjianBian_Click(object sender, EventArgs e)
        //{
        //    Brush brush = new LinearGradientBrush(new RectangleF(0, 0, textBox1.Width, textBox1.Height), Color.Red, Color.Blue, 0.0);
        //    Graphics graphics = textBox1.CreateGraphics();
        //    graphics.DrawString("文字颜色渐变", new Font("宋体", 20, FontStyle.Bold), brush, new PointF(0, 0));
        //}
        /// <summary>
        /// 绘制四个按钮图片
        /// </summary>
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            //开始
            SetBG("1.jpg");
            Graphics startg = Graphics.FromImage(Start);
            startg.FillEllipse(Brushes.Blue, new RectangleF(0, 0, Start.Width, Start.Height));
            //上一曲
            Graphics upg = Graphics.FromImage(UpSong);
            upg.FillPolygon(Brushes.Blue, new PointF[] { new PointF(0, 10), new PointF(20, 0), new PointF(20, 20) });
            pictureBox4.Image = UpSong;
            //下一曲
            Graphics nex = Graphics.FromImage(NextSong);
            nex.FillPolygon(Brushes.Blue, new PointF[] { new PointF(0, 0), new PointF(20, 10), new PointF(0, 20) });
            pictureBox3.Image = NextSong;
            //暂停
            Graphics pau = Graphics.FromImage(Pause);
            pau.FillPolygon(Brushes.Red, new PointF[] { new PointF(0, 0), new PointF(20, 0), new PointF(20, 20),new PointF(0,20) });
           // pictureBox2.Image = Pause;
            //渐变
            //Brush brush = new LinearGradientBrush(new RectangleF(0, 0, textBox1.Width, textBox1.Height), Color.Red, Color.Blue, 0.0);
            //Graphics graphics = textBox1.CreateGraphics();
            //graphics.DrawString("文字颜色渐变", new Font("宋体", 20, FontStyle.Bold), brush, new PointF(0, 0));
        }
        //背景
        FileInfo info;
        private void SetBG(string file)
        {
            Image image = Image.FromFile("../../img/" + file);
            Bitmap bg = new Bitmap(300, 300);
            Graphics graphics = Graphics.FromImage(bg);
            graphics.DrawImage(image, new Rectangle(0, 0, bg.Width, bg.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
            pictureBox1.Image = bg;
        }
        /// <summary>
        /// 装背景图
        /// </summary>
        List<string> bgList = new List<string>();
        /// <summary>
        /// 背景图索引
        /// </summary>
        int bgIndex = 0;
        private void 更换背景ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bgIndex++;
            if (bgIndex>=bgList.Count)
            {
                bgIndex = 0;
            }
            SetBG(bgList[bgIndex]);
        }
        /// <summary>
        /// 暂停和播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            if (axWindowsMediaPlayer1.playState== WMPLib.WMPPlayState.wmppsPlaying)
            {
                pictureBox2.Image = Start;
                axWindowsMediaPlayer1.Ctlcontrols.pause();
            }
            else if (axWindowsMediaPlayer1.playState== WMPLib.WMPPlayState.wmppsPaused)
            {
                pictureBox2.Image = Pause;
                axWindowsMediaPlayer1.Ctlcontrols.play();
            }
        }
        /// <summary>
        /// 上一曲
        /// </summary>
        private void pictureBox4_Click(object sender, EventArgs e)
        {
            if (graphics1!=null)
            {
                graphics1.Clear(Color.Cyan);
                currentindex--;
                if (currentindex < 0)
                {
                    currentindex = listBox1.Items.Count - 1;
                }
                PlayMusic(musicPath[currentindex]);
                listBox1.SelectedItem = musicList[currentindex];
            }
        }
        /// <summary>
        /// 下一曲
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox3_Click(object sender, EventArgs e)
        {
            NextMusic();

        }
        /// <summary>
        /// 下一曲的方法
        /// </summary>
        private void NextMusic()
        {
            if (graphics1!=null)
            {
                graphics1.Clear(Color.Cyan);
                currentindex++;
                if (currentindex>=musicList.Count)
                {
                    currentindex = 0;
                }
                PlayMusic(musicPath[currentindex]);
                listBox1.SelectedItem = musicList[currentindex];
            }
        }
        /// <summary>
        /// 播放音乐的方法
        /// </summary>
        /// <param name="o"></param>
        private void PlayMusic(string o)
        {
            musicChar.Clear();
            musicTime.Clear();
            if (graphics1!=null)
            {
                graphics1.Clear(Color.Cyan);
            }
            axWindowsMediaPlayer1.URL = o;
            axWindowsMediaPlayer1.Ctlcontrols.play();

            int lastIndex = o.LastIndexOf(".");
            //歌词文件
            o = o.Remove(lastIndex) + ".lrc";
            //o已经是歌词文件的完整路径
            try
            {
                StreamReader reader = new StreamReader(o,Encoding.Default);
                musicString = reader.ReadToEnd();
                musicChar.AddRange(musicString.Split('\n'));
                if (musicChar.Count>0)
                {
                    foreach (var item in musicChar)
                    {
                        string[] str = item.Split('[', ']');
                        string[] tineStr = str[1].Split(':');
                        float times = float.Parse(tineStr[0]) * 60 + float.Parse(tineStr[1]);
                        musicTime.Add(times);
                    }
                }
            }
            catch (Exception)
            {
                musicString = "未找到对应歌词!";
            }
        }

        Graphics graphics1;
        Graphics graphics2;
        private void timer1_Tick(object sender, EventArgs e)
        {
            float prent = 0;
            if (axWindowsMediaPlayer1.currentMedia!=null)
            {
                //判断开始和暂停按钮
                if (axWindowsMediaPlayer1.playState==WMPLib.WMPPlayState.wmppsPlaying)
                {
                    pictureBox2.Image = Pause;
                }
                else if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsPaused)
                {
                    pictureBox2.Image = Start;
                }
                //设置lable------音乐进度
                label1.Text = axWindowsMediaPlayer1.currentMedia.durationString;
                label2.Text = axWindowsMediaPlayer1.Ctlcontrols.currentPositionString;
                double duration = axWindowsMediaPlayer1.currentMedia.duration;
                double current = axWindowsMediaPlayer1.Ctlcontrols.currentPosition;
                prent = (float)current / (float)duration;
                graphics1 = panel1.CreateGraphics();
                graphics1.FillRectangle(Brushes.Red, new RectangleF(0, 0, panel1.Width * prent, panel1.Height));
               

                if (axWindowsMediaPlayer1.Ctlcontrols.currentPositionString != "")
                {
                    //截取播放的时间
                    string[] currentPosition = axWindowsMediaPlayer1.Ctlcontrols.currentPositionString.Split(':');

                    float nowTime = float.Parse(current.ToString("f2"));
                    if (musicTime.Count==0)
                    {
                        textBox1.Text = "未找到对应歌词!";
                    }
                    for (int i=0;i<musicTime.Count;i++)
                    {
                        if (nowTime >= musicTime[i])
                        {
                            string[] charList = musicChar[i].Split(']');
                            if (charList[1]=="")
                            {
                                charList = musicChar[i - 1].Split(']');
                                textBox1.Text = charList[1];
                            }
                            else
                            {
                                textBox1.Text = charList[1];
                            }
                        }
                    }
                }
            }
            
           ///判断音乐播放完成自动播放下一曲
            if (prent > 0.999f)
            {
                NextMusic();
            }
        }
        /// <summary>
        /// 音乐进度条点击时快进快退
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel1_MouseClick(object sender, MouseEventArgs e)
        {
            if (graphics1!=null&& axWindowsMediaPlayer1.currentMedia != null)
            {
                graphics1.Clear(Color.Cyan);
                graphics1.FillRectangle(Brushes.Red, new RectangleF(0, 0, e.X, panel1.Height));
                float prent = (float)e.X / (float)panel1.Width;
                double duration = axWindowsMediaPlayer1.currentMedia.duration;
                double current = duration * prent;
                axWindowsMediaPlayer1.Ctlcontrols.currentPosition = current;
            }
        }
        private void panel2_MouseClick(object sender, MouseEventArgs e)
        {
            //尽量在使用控件时进行空指针判断
            if (graphics2 != null)
            {
                graphics2.Clear(Color.Silver);
                graphics2.FillRectangle(Brushes.Cyan, new RectangleF(0, 0, e.X, panel2.Height));
                double  prent = (double)e.X /(double)panel2.Width;
                double  currents = 100 * prent;
                axWindowsMediaPlayer1.settings.volume = Convert.ToInt32(currents);
                label4.Text = axWindowsMediaPlayer1.settings.volume.ToString();
            }
        }
        private void panel2_Paint(object sender, PaintEventArgs e)
        {
            graphics2.FillRectangle(Brushes.Cyan, new RectangleF(0, 0, panel2.Width * 0.5f, panel2.Height));
        }
    }
}

效果图:
在这里插入图片描述
点击加载音乐可以打开电脑中文件夹选择要加载的音乐
在这里插入图片描述

在这里插入图片描述
如果选择的音乐在电脑的文件夹里包含歌词 ,音乐播放是显示歌词
在这里插入图片描述
点击音乐播放的进度条可调节播放进度,音量也可以通过点击进度条调节音量
在这里插入图片描述
同时右击背景图可更换背景

posted on 2019-02-06 12:34  豆皮没有豆  阅读(332)  评论(0)    收藏  举报