C# DirectShow 播放多媒体
    C# DirectShow 播放多媒体 
2011年12月01日
  要使 C# 代码引用 COM 对象和接口,需要在 C# 内部版本中包含 COM 接口的 .NET 框架定义。完成此操作的最简单方法是使用 TlbImp.exe(类型库导入程序),它是一个包括在 .NET 框架 SDK 中的命令行工具。TlbImp 将 COM 类型库转换为 .NET 框架元数据,从而有效地创建一个可以从任何托管语言调用的托管包装。用 TlbImp 创建的 .NET 框架元数据可以通过 /R 编译器选项包括在 C# 内部版本中。如果使用 Visual Studio 开发环境,则只需添加对 COM 类型库的引用,将为您自动完成此转换。 
  例如,我们要播放当前目录下的demo.avi文件,需要用到包含在位于 Windows 系统目录中的 Quartz.dll 中的媒体播放机。(c:\winnt\system32\quartz.dll)。可在命令行中运行TlbImp文件(D:\ Microsoft Visual Studio .NET\FrameworkSDK\Bin\Tlbimp.exe) 
  tlbimp c:\winnt\system32\quartz.dll /out:QuartzTypeLib.dll 
  请注意,得到的 DLL 需要命名为 QuartzTypeLib,以便 .NET 框架可以在运行时正确加载包含类型。 
  生成程序时使用 C# 编译器选项 /R 以包含 QuartzTypeLib.dll 文件;如果使用 Visual Studio 开发环境,直接添加引用即可(using QuartzTypeLib)。 
  然后就可以使用此程序显示影片了。 
  具体编写代码时,用到了RenderFile 和 Run 方法。例: 
  private void menuItemOpen_Click(object sender, System.EventArgs e) 
  { 
  FilgraphManager m_FilGraphManager = null; 
  IBasicAudio m_BasicAudio = null; 
  IVideoWindow m_VideoWindow = null; 
  IMediaEvent m_MediaEvent = null; 
  IMediaEventEx m_MediaEventEx = null; 
  IMediaPosition m_MediaPosition = null; 
  IMediaControl m_MediaControl = null; 
  OpenFileDialog  OpenDialog = new OpenFileDialog(); 
  OpenDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";                //本例用对话框读入要显示的影片文件名 
  if (DialogResult.OK == OpenDialog.ShowDialog()) 
  { 
  m_FilGraphManager = new FilgraphManager();               
  m_FilGraphManager.RenderFile(OpenDialog.FileName); 
  m_BasicAudio = m_FilGraphManager as IBasicAudio ; 
  try 
  { 
  m_VideoWindow = m_FilGraphManager as IVideoWindow; 
  m_VideoWindow.Owner = (int) panel1.Handle; 
  m_VideoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN; 
  //此设置可以不显示播放器的title,使播放器像嵌在窗体中。 
  //可设置 private const int WS_CHILD = 0x40000000; 
  //      private const int WS_CLIPCHILDREN = 0x2000000; 
  m_VideoWindow.SetWindowPosition(panel1.ClientRectangle.Left, 
  panel1.ClientRectangle.Top, 
  panel1.ClientRectangle.Width, 
  panel1.ClientRectangle.Height); 
  // 在panel1中显示,要求影片可随panel1大小而变化。 
  } 
  catch (Exception) 
  { 
  m_VideoWindow = null; 
  }
  m_MediaEvent = m_FilGraphManager as IMediaEvent; 
  m_MediaEventEx = m_FilGraphManager as IMediaEventEx; 
  m_MediaEventEx.SetNotifyWindow((int) this.Handle,WM_GRAPHNOTIFY, 0); 
  m_MediaPosition = m_FilGraphManager as IMediaPosition; 
  m_MediaControl = m_FilGraphManager as IMediaControl; 
  this.Text = "DirectShow - [" + OpenDialog.FileName + "]"; 
  m_MediaControl.Run(); 
  } 
  }
  也可以加入pause,stop命令来控制影片的播放。 
  m_MediaControl.Pause() 
  m_MediaControl.Stop()