Home [C# 筆記][WinForm] ListBox 實現點擊播放音樂
Post
Cancel

[C# 筆記][WinForm] ListBox 實現點擊播放音樂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//用來儲存音樂全路徑
List<string> listSongs = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
    //取得指定文件夾中的所有音樂的全路徑
    string[] path = Directory.GetFiles(@"C:\Users\rivalin\Desktop\music", "*.wav");
    for (int i = 0; i < path.Length; i++)
    {
        //取得音樂檔名
        string filename = Path.GetFileName(path[i]);

        //音樂檔名加入listBox2中
        listBox2.Items.Add(filename);

        //將音樂檔案路徑加到list泛型集合中
        listSongs.Add(path[i]);
    }
}

/// <summary>
/// 雙擊播放音樂
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBox2_DoubleClick(object sender, EventArgs e)
{
    SoundPlayer sp = new SoundPlayer();
    sp.SoundLocation = listSongs[listBox2.SelectedIndex];
    sp.Play();
}
This post is licensed under CC BY 4.0 by the author.