一 個簡單的基於DirectShow的打開本地視頻文件的例子。ide
參考了各類資材,網上不少,也比較簡單,但有個問題就是在調用" RenderFile "函數時只有在x86下都會返回S_OK,很費解。。。待繼續深刻研究一下。函數
代碼:ui
IGraphBuilder *gGraph = NULL; IMediaControl *gControl = NULL; IMediaEvent *gEvent = NULL;
bool CreateSimplerPlayer(PTSTR pstrFileName) { // init com HRESULT hr = CoInitialize(NULL); if (FAILED(hr)) return false; // init gragh builder hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void**)&gGraph); if (FAILED(hr)) return false; // query controler interface in graphbuilder hr = gGraph->QueryInterface(IID_IMediaControl, (void**)&gControl); if (FAILED(hr)) return false; // query event interface in graphbuilder hr = gGraph->QueryInterface(IID_IMediaEvent, (void**)&gEvent); if (FAILED(hr)) return false; hr = gGraph->QueryInterface(IID_IBasicVo, (void**)&gVideo); if (FAILED(hr)) return false; // read a file hr = gGraph->RenderFile(pstrFileName, NULL); if (!FAILED(hr)) { hr = gControl->Run(); if (SUCCEEDED(hr)) { long evCode; gEvent->WaitForCompletion(INFINITE, &evCode); return true; } } return false; }
主要就是RenderFile,只要選擇播放的文件,IGraphBuilder就智能地幫你構造出整個Filter Graph。spa
下面是在控制檯程序中打開文件管理對話框的代碼,選擇好文件後將文件路徑傳給CreateSimplerPlayer。code
代碼:視頻
TCHAR szBuffer[MAX_PATH] = { 0 }; OPENFILENAME file = { 0 }; file.hwndOwner = NULL; file.lStructSize = sizeof(file); file.lpstrFilter = _T("全部文件(*.*)\0*.*\0Exe文件(*.exe)\0*.exe\0");//要選擇的文件後綴 file.lpstrInitialDir = _T("E:\\");//默認的文件路徑 file.lpstrFile = szBuffer;//存放文件的緩衝區 file.nMaxFile = sizeof(szBuffer) / sizeof(*szBuffer); file.nFilterIndex = 0; file.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER;//標誌若是是多選要加上OFN_ALLOWMULTISELECT BOOL bSel = GetOpenFileName(&file); //cout << file.lpstrFile << endl; SimplePlayer::CreateSimplerPlayer(file.lpstrFile);