小弟正在学习C#,在做一个MP3播放器,
选择文件或文件夹把里面的文件名添加到的listbox1里面,然后双击listbox1中的项进行播放
string a = listBox1.SelectedItem.ToString();
axWindowsMediaPlayer1.URL = @"D:\KuGou\" + a;
但我这么写是写死的了,请问怎么根据listbox1中的项(文件名)获取他所在的路径?
具体代码如下:
//添加音频文件的文件名到listbox
private void button4_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "*.mp3(mp3文件)|*.mp3";
open.Multiselect=true;
open.ShowDialog();
foreach (string item in open.SafeFileNames)
{
listBox1.Items.Add(item);
}
}
//添加文件夹内音频文件的文件名到listbox
private void button5_Click(object sender, EventArgs e)
{
FolderBrowserDialog dir = new FolderBrowserDialog();
if (dir.ShowDialog()==DialogResult.OK)
{
string a = dir.SelectedPath;
string[] str = Directory.GetFiles(a);
string[] newname = new string[str.Length];
for (int i = 0; i < str.Length; i++)
{
newname[i] = Path.GetFileName(str[i]);
}
foreach (string item in newname)
{
if(item.EndsWith(".mp3")||item.EndsWith(".wma")||item.EndsWith(".wav"))
{
listBox1.Items.Add(item);
}
}
}
}
//播放列表中的文件
private void listBox1_DoubleClick(object sender, EventArgs e)
{
try
{
string a = listBox1.SelectedItem.ToString();
//播放音频文件
axWindowsMediaPlayer1.URL = @"D:\KuGou\" + a;
}
catch
{
return;
}
}
axWindowsMediaPlayer1.URL = @"D:\KuGou\" + a;
还有就是感觉我这样写特别别扭,如果有两个相同文件名而菜价所在路径不同,那播放谁的。
求教一下怎么根据listbox1中的项(文件名)获取他所在的路径?有没有好的方法不用axWindowsMediaPlayer1.URL = @"D:\KuGou\" + a; 这样写的啊?谢谢。
------解决思路----------------------
struct Song
{
public string Name;
public string Filename;
public Song(string name, string filename)
{
Name = name;
Filename = filename;
}
public override string ToString()
{
return Name;
}
public override bool Equals(object obj)
{
if (obj.GetType() == typeof(Song))
{
return Filename.Equals(((Song)obj).Filename);
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return Filename.GetHashCode();
}
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "*.mp3(mp3文件)
------解决思路----------------------
*.mp3";
open.Multiselect = true;
if (open.ShowDialog() == DialogResult.OK)
{
for (int i = 0; i < open.FileNames.Length; i++)
{
Song song = new Song(System.IO.Path.GetFileName(open.FileNames[i]), open.FileNames[i]);
if (!listBox1.Items.Contains(song))
{
listBox1.Items.Add(song);
}
}
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
this.Text = ((Song)listBox1.SelectedItem).Filename;
}
else
{
this.Text = "当前没有选择歌曲";
}
}
如果这个不行的话,我发代码到你邮箱
------解决思路----------------------
你有没有绑定事件?
窗口初始化时加一下这一句
this.listBox1.Format += new System.Windows.Forms.ListControlConvertEventHandler(this.listBox1_Format);