1 加载COM组件,把Windows Media Player控件拖放到Winform窗体中
工具--》选择工具箱项--》COM组件--》Windows Media Player
2 音乐播放器
playbutton 播放 lastbutton 上一曲 nextbutton 下一曲 openbutton打开文件 axWindowMediaPlayer 播放器组件
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//用来存储音乐文件的全路径
List<string> listSong = new List<string>();
private void openbutton_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "请选择文件";
ofd.Multiselect = true;
ofd.InitialDirectory = @"D:\queena.pan\桌面\record\wav";
ofd.Filter = "音乐文件|*.wav|mp3文件|*.mp3|所有文件|*.*";
ofd.ShowDialog();
//获得我们在文件夹中选择所有文件的全路径
string[] path = ofd.FileNames;
for(int i=0;i<path.Length;i++)
{
//将音乐文件的文件名加载到ListBox中
listBox1.Items.Add(Path.GetFileName(path[i]));
//将音乐文件的全路径存储到泛型集合中
listSong.Add(path[i]);
}
}
private void playbutton_Click(object sender, EventArgs e)
{
if(playbutton.Text=="播放")
{
axWindowsMediaPlayer1.URL = listSong[listBox1.SelectedIndex];
axWindowsMediaPlayer1.Ctlcontrols.play();
playbutton.Text = "暂停";
}
else
{
axWindowsMediaPlayer1.Ctlcontrols.pause();
playbutton.Text = "播放";
}
}
private void lastbutton_Click(object sender, EventArgs e)
{
// 获得当前选中歌曲的索引
int index = listBox1.SelectedIndex;
index--;
if (index < 0)
{
index = listBox1.Items.Count - 1;
}
//将重新改变后的索引重新的赋值给当前选中项
listBox1.SelectedIndex = index;
axWindowsMediaPlayer1.URL = listSong[index];
axWindowsMediaPlayer1.Ctlcontrols.play();
}
private void nextbutton_Click(object sender, EventArgs e)
{
int index = listBox1.SelectedIndex;
index++;
if (index==listBox1.Items.Count)
{
index = 0;
}
listBox1.SelectedIndex = index;
axWindowsMediaPlayer1.URL = listSong[index];
axWindowsMediaPlayer1.Ctlcontrols.play();
}
}