使用Windows Media Player 其实就是使用组件AxWindowsMediaPlayer。
添加两个引用:Interop.WMPLib.dll和AxInterop.WMPLib.dll。
添加命名空间using AxWMPLib;
在使用时还有两个基本的条件:1、控件要依附在某个父控件上,比如form,panel;因为这样可以让组件保持长期性(网上这样说)。2、依附的控件是要有句柄;3、在使用前进行如下的初始化:
((System.ComponentModel.ISupportInitialize)(this.ax1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ax1)).EndInit();
第一种情况不满足时,出现错误“System.Windows.Forms.AxHost+InvalidActiveXStateException”的异常,解决的办法可以像这样:
AxWindowsMediaPlayer ax1 = new AxWindowsMediaPlayer(); Form f = new Form(); f.Controls.Add(ax1);
但是,这个Form不是按常规来创建的,据个人猜测是没有执行像CreateWindow类似的函数吧。所以它是没有句柄的,这样情况出现如下:
在一个类库中想使用AxWindowsMediaPlayer,并且使用了多线程:
1 class DDX 2 { 3 AxWindowsMediaPlayer ax1 = new AxWindowsMediaPlayer(); 4 Form f = new Form();//为了满足条件1 5 6 public delegate void STARTSOUND(bool b);//委托,副线程中调用主线程上的组件 7 8 public DDX() 9 { 10 int i = f.Handle;//这是为了满足条件2,这样操作的作用是强制为f创建句柄,以使Invoke方法能执行 11 } 12 void button1_click(object o,EventArgs e) 13 { 14 new Thread(new ThreadStart(InmoitorFun)).start(); 15 } 16 17 void InmoitorFun()//因为是在线程中,所以要使用控件的Invoke来调用方法,ax1是在主线程中创建的 18 { 19 while(true) 20 { 21 ... 22 f.Invoke(new STARTSOUND(StartSound),new object[]{false});//一定要有前面的int i = f.Handle,不然会出现异常,Invoke方法执行的条件 23 ... 24 } 25 } 26 27 void StartSound(bool b) 28 { 29 ((System.ComponentModel.ISupportInitialize)(this.ax1)).BeginInit();//还要进行初始化,为了满足第3个条件, 30 ((System.ComponentModel.ISupportInitialize)(this.ax1)).EndInit(); 31 ax1.URL="F:\1.mp3"; 32 ax1.settings.setMode("loop",true); 33 ax1.play(); 34 } 35 }