image.png

    1. using System;
    2. using System.Collections.Generic;
    3. using System.ComponentModel;
    4. using System.Data;
    5. using System.Drawing;
    6. using System.IO;
    7. using System.Linq;
    8. using System.Media;
    9. using System.Text;
    10. using System.Threading.Tasks;
    11. using System.Windows.Forms;
    12. namespace _121_播放音乐上一曲下一曲
    13. {
    14. public partial class Form1 : Form
    15. {
    16. public Form1()
    17. {
    18. InitializeComponent();
    19. }
    20. List<string> listSongs = new List<string>();
    21. //Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
    22. private void button1_Click(object sender, EventArgs e)
    23. {
    24. OpenFileDialog ofd = new OpenFileDialog();
    25. ofd.Title = "请选择音乐文件";
    26. ofd.InitialDirectory = @"C:\Users\46124\Desktop\.wav音乐";
    27. ofd.Multiselect = true;
    28. ofd.Filter = "媒体文件|*.wav|所有文件|*.*";
    29. ofd.ShowDialog();
    30. //获得我们在文件夹中选择所有文件的全路径
    31. string[] path = ofd.FileNames;
    32. foreach (var item in path)
    33. {
    34. listBox1.Items.Add(Path.GetFileNameWithoutExtension(item));
    35. //将音乐文件存储到泛型集合中
    36. listSongs.Add(item);
    37. //keyValuePairs.Add(Path.GetFileNameWithoutExtension(item), item);
    38. }
    39. }
    40. SoundPlayer sp = new SoundPlayer();
    41. /// <summary>
    42. /// 实现双击播放音乐
    43. /// </summary>
    44. /// <param name="sender"></param>
    45. /// <param name="e"></param>
    46. private void listBox1_DoubleClick(object sender, EventArgs e)
    47. {
    48. sp.SoundLocation = listSongs[listBox1.SelectedIndex];
    49. //sp.SoundLocation = keyValuePairs[listBox1.Items.ToString()];
    50. sp.Play();
    51. }
    52. /// <summary>
    53. /// 点击下一曲
    54. /// </summary>
    55. /// <param name="sender"></param>
    56. /// <param name="e"></param>
    57. private void button3_Click(object sender, EventArgs e)
    58. {
    59. //获得当前选中歌曲的索引
    60. int index = listBox1.SelectedIndex;
    61. index++;
    62. if (index == listBox1.Items.Count)
    63. {
    64. index = 0;
    65. }
    66. //将改变后的索引重新赋值给我当前项中的索引,实现蓝条移动
    67. listBox1.SelectedIndex = index;
    68. sp.SoundLocation = listSongs[index];
    69. sp.Play();
    70. }
    71. /// <summary>
    72. /// 点击上一曲
    73. /// </summary>
    74. /// <param name="sender"></param>
    75. /// <param name="e"></param>
    76. private void button2_Click(object sender, EventArgs e)
    77. {
    78. //获得当前选中歌曲的索引
    79. int index = listBox1.SelectedIndex;
    80. index--;
    81. if (index < 0)
    82. {
    83. index = listBox1.Items.Count - 1;
    84. }
    85. //将改变后的索引重新赋值给我当前项中的索引,实现蓝条移动
    86. listBox1.SelectedIndex = index;
    87. sp.SoundLocation = listSongs[index];
    88. sp.Play();
    89. }
    90. }
    91. }