DirectShow 是 Windows 多媒體串流架構,核心元件位於 C:\Windows\System32\quartz.dll。C# 專案需將此 COM 類型庫轉換為 .NET 組件(Interop 組件)才能引用。本文記錄完整建置步驟與常用介面對照表。
工具路徑(視 VS 安裝位置而定):
D:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\TlbImp.exe
TlbImp C:\Windows\System32\quartz.dll /out:QuartzDirectShow.dll
QuartzDirectShow.dllQuartzDirectShow.dllusing QuartzDirectShow; // 或 quartzDriectShow(視轉換時大小寫)
| 介面 | 用途 | 關鍵方法/屬性 |
|---|---|---|
IFilterGraph | 基本濾鏡圖管理 | AddFilter, RemoveFilter, Connect, EnumFilters |
IFilterGraph2 | 增強版濾鏡圖 | AddSourceFilterForMoniker, ReconnectEx |
IGraphBuilder | 手動/自動建構濾鏡圖 | RenderFile, Render, ConnectDirect |
IMediaControl | 串流播放控制 | Run, Stop, Pause, GetState |
IMediaEvent | 播放事件通知 | GetEventHandle, WaitForCompletion, FreeEventParams |
IMediaEventEx | 擴展事件視窗 | SetNotifyWindow, SetNotifyFlags |
IMediaPosition | 時間基準位置/速度控制 | CurrentPosition, StopTime, Rate, put_CurrentPosition |
IMediaSeeking | 進階位置/速度控制 | SetPositions, GetDuration, GetCurrentPosition, SetRate |
IBasicAudio | 音量/平衡控制 | Volume, Balance |
IBasicVideo | 影像屬性查詢 | VideoWidth, VideoHeight, BitRate, BitErrorRate |
IVideoWindow | 視訊視窗控制 | Owner, WindowStyle, SetWindowPosition, put_Caption |
ISampleGrabber | 影格擷取/截圖 | SetCallback, GetCurrentBuffer, SetBufferSamples |
IVideoFrameStep | 單步幀控制 | Step, CanStep, CancelStep |
CoCreateInstance 建立 Filter Graph Manager,QueryInterface 取得所需介面Marshal.ReleaseComObject 或 RCW 自然回收,確保資源釋放IMediaEvent 需配合視窗訊息迴圈或 WaitForCompletion 取得事件MediaFoundation、LibVLCSharp、FFmpeg.NET 等跨平台庫// 1. 建立 Graph Builder
IGraphBuilder graph = (IGraphBuilder)new FilterGraph();
// 2. 載入媒體檔
graph.RenderFile(@"C:\Video\sample.mp4", null);
// 3. 取得控制介面
IMediaControl control = (IMediaControl)graph;
IVideoWindow vw = (IVideoWindow)graph;
// 4. 設定視訊視窗
vw.Owner = this.Handle; // WinForm 控制項 Handle
vw.WindowStyle = 0x40000000 | 0x10000000; // WS_CHILD | WS_CLIPCHILDREN
vw.SetWindowPosition(0, 0, this.Width, this.Height);
// 5. 播放
control.Run();
// 6. 釋放(FormClosing 事件中)
control.Stop();
Marshal.ReleaseComObject(vw);
Marshal.ReleaseComObject(control);
Marshal.ReleaseComObject(graph);
提示: 實際專務建議封裝為 IDisposable 元件,統一管理 COM 物件生命週期。