using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 音樂播放器
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//添加音樂文件
private void btn_add_Click(object sender, EventArgs e)
{
//實例化一個文件對話框
OpenFileDialog fd = new OpenFileDialog();
//設置對話框屬性:標題
fd.Title = "選擇音樂文件";
//設置文件擴展名篩選
fd.Filter = "(音樂文件).mp3.mp4.wav|*.mp3;*.mp4;*.wav;";
//設置多選
fd.Multiselect = true;
//顯示對話框
DialogResult dr = fd.ShowDialog();
if (dr == DialogResult.OK) //點擊的是確定按鈕
{
//獲取所有選擇的音樂文件名--數組
string[] fns = fd.FileNames;
//把選擇的音樂文件名添加到列表框ListBox
foreach (string fn in fns)
{
this.listBox1.Items.Add(fn);
}
}
}
private void btn_bf_Click(object sender, EventArgs e)
{
if (this.listBox1.SelectedIndex == -1)
{ //如果沒有選中歌曲,默認選擇第一首
this.listBox1.SelectedIndex = 0;
}
//播放音樂 = 獲取列表框的當前選中項
this.wmp_mm.URL = this.listBox1.SelectedItem.ToString();
//啟動定時器
this.timer1.Start();
}
//時時刻刻檢測播放器是否播放完畢
int s = 0;
private void timer1_Tick(object sender, EventArgs e)
{
//設置進度條的進度
if (s <= this.progressBar1.Maximum) //不能超過進度條的上限
{
this.progressBar1.Value = s++;
}
//如果播放器的播放狀態為停止狀態 Ctrl+J
if (this.wmp_mm.playState == WMPLib.WMPPlayState.wmppsStopped)
{
//設置列表框選中下一個
int xb = this.listBox1.SelectedIndex;
xb++;
if (xb == this.listBox1.Items.Count)
{ //如果到了最后一首,回到第一首
xb = 0;
}
this.listBox1.SelectedIndex = xb;
//設置播放器URL
this.wmp_mm.URL = this.listBox1.SelectedItem.ToString();
}
}
}
}
//因為工具箱沒有音樂播放工具 我們要導入windows自帶的播放器
添加播放器控件說明:
第一步:添加選項卡-為選項卡命名
第二步:在這個選項卡里面右鍵->選擇項
第三步:找到COM組件->Windows Media Player
//窗體UI設計