.net winform 可以使用 System.Media.SoundPlayer 播放音频,但如何想控制暂停和停止,还是有些麻烦的.
使用第三方类库 AxInterop.WMPLib.dll 可轻松实现该功能,并可以实现音频心跳
核心代码如下:
private WMPLib.WindowsMediaPlayerClass c;
private WMPLib.IWMPMedia m;
private void zbtnopen_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true; //该值确定是否可以选择多个文件
dialog.Title = "UF请选择文件"; //弹窗的标题
dialog.InitialDirectory = "D:\\"; //默认打开的文件夹的位置
dialog.Filter = "MicroSoft Excel文件(*.mp3)|*.mp3|MicroSoft Excel文件(*.wav)|*.wav|所有文件(*.*)|*.*"; //筛选文件
dialog.FilterIndex = 2; //指定筛选默认索引
dialog.ShowHelp = false; //是否显示“帮助”按钮
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
zlblfile.Text = dialog.FileName;
c = new WMPLib.WindowsMediaPlayerClass();
m = c.newMedia(dialog.FileName);
this.zaxw.URL = dialog.FileName;
}
}
private void zbtstart_Click(object sender, EventArgs e)
{
this.zaxw.Ctlcontrols.play();
}
private void zbtnsuspend_Click(object sender, EventArgs e)
{
this.zaxw.Ctlcontrols.pause();
}
private void zbtstop_Click(object sender, EventArgs e)
{
this.zaxw.Ctlcontrols.stop();
}
实现效果: