C#做一个简单的音乐播放器

界面:

在这里插入图片描述
点击打开单选音乐文件或多选,音乐文件名被添加到旁边的listBox控件中,按上一曲下一曲切换歌曲
添加的引用:

using System.IO;
using System.Media;

设置的全局变量:

List<string> listSongs = new List<string>();//用来存储音乐文件的全部路径
SoundPlayer sp = new SoundPlayer(); 	//用于播放音乐的控件

打开代码:

			OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "请选择音乐文件";
            ofd.InitialDirectory = @"C:\Users\刘熙\Desktop\music";
            ofd.Multiselect = true;
            ofd.Filter = "音乐文件|*.mp3|所有文件|*.*";
            ofd.ShowDialog();
            //获取所有选择的路径
            string[] path = ofd.FileNames;

            for (int i = 0; i < path.Length; i++)
            {
                //将音乐文件加载到list中
                listBox1.Items.Add(Path.GetFileName(path[i]));
                //将音乐文件的全路径存储在集合中
                listSongs.Add(path[i]);

            }

双击listBox中的项播放音乐(在listbox中添加doubleclick事件):

			try    //捕获播放中可能出现的错误,例如:不支持的文件类型
            {
                
                sp.SoundLocation = listSongs[listBox1.SelectedIndex];			//指定播放音乐的路径
                sp.Play();			//播放
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }

上一曲:

			try
            {
                //获取当前选中索引
                int index = listBox1.SelectedIndex;
                index++;
                if (index == listBox1.Items.Count)			//判断选中的索引值是否为最大,是就修改为0
                {
                    index = 0;
                }
                //将改变后索引重新赋值,使选中状态改变
                listBox1.SelectedIndex = index;
                sp.SoundLocation = listSongs[index];		//指定播放音乐的路径
                sp.Play();		//播放
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
            }

下一曲:

int index = listBox1.SelectedIndex;
            index--;
            if (index < 0)
            {
                index = listBox1.Items.Count - 1;
            }
            listBox1.SelectedIndex = index;
            sp.SoundLocation = listSongs[index];
            sp.Play();

测试了,可以打开wav类型的音乐文件,打开mp3的会弹出不是有效的波形文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值