界面:
点击打开单选音乐文件或多选,音乐文件名被添加到旁边的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的会弹出不是有效的波形文件。