一、实现添加多个歌曲功能
首先创建一个窗体,添加相应控件,如图显示:
双击打开按钮,写入如下代码:
/// <summary>
/// 音乐播放路径
/// </summary>
List<String> pathList = new List<string>();
/// <summary>
/// 打开音乐功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//文件对话框设置
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "选择音乐文件";
ofd.Multiselect = true;
ofd.InitialDirectory = @"H:\c#\传播智客\项目\第十六天\Music";
ofd.Filter = "音乐文件|*.wav|所有文件|*.*";
ofd.ShowDialog();
//添加到Listbox中
string[] path = ofd.FileNames;
for (int i = 0; i < path.Length; i++)
{
listBox1.Items.Add(Path.GetFileName(path[i]));//将歌曲文件名添加到listbox中
pathList.Add(path[i]);//将歌曲路径添加到集合中,用于后面实现双击播放音乐
}
}
二、实现双击播放音乐
/// <summary>
/// 播放音乐
/// </summary>
SoundPlayer sp = new SoundPlayer();
private void listBox1_DoubleClick(object sender, EventArgs e)
{
string path = pathList[this.listBox1.SelectedIndex];//拿到当前选中的路径
sp.SoundLocation = path;
sp.Play();
}
现在,你已经可以双击播放一首音乐啦!——支持.wav格式的音乐
三、实现上一曲
/// <summary>
/// 上一曲实现
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
int index = this.listBox1.SelectedIndex;
index--;
//判断是否为第一首歌
if (index<0)
{
index = this.pathList.Count - 1;
}
//将新索引赋值给当前项,否则listbox的蓝色选中框会不变
this.listBox1.SelectedIndex = index;
//播放音乐
string path = pathList[index];//拿到当前选中的路径
sp.SoundLocation = path;
sp.Play();
}
四、实现下一曲
/// <summary>
/// 下一曲
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
int index = this.listBox1.SelectedIndex;
index++;
//判断是否为最后一首歌
if (index == this.pathList.Count)
{
index = 0;
}
//将新索引赋值给当前项,否则listbox的蓝色选中框会不变
this.listBox1.SelectedIndex = index;
//播放音乐
string path = pathList[index];//拿到当前选中的路径
sp.SoundLocation = path;
sp.Play();
}