列舉視訊擷取裝置

本主題描述如何列舉使用者系統上的視訊擷取裝置,以及如何建立裝置的實例。

若要列舉系統上的視訊擷取裝置,請執行下列動作:

  1. 呼叫 MFCreateAttributes 以建立屬性存放區。 此函式會收到 IMFAttributes 指標。
  2. 呼叫 IMFAttributes::SetGUID 以設定 MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE 屬性。 將屬性值設定為 MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
  3. 呼叫 MFEnumDeviceSources。 此函式會接收 IMFActivate 指標和陣列大小的陣列。 每個指標都代表不同的視訊擷取裝置。

若要建立擷取裝置的實例:

下列程式碼顯示這些步驟:

HRESULT CreateVideoDeviceSource(IMFMediaSource **ppSource)
{
    *ppSource = NULL;

    IMFMediaSource *pSource = NULL;
    IMFAttributes *pAttributes = NULL;
    IMFActivate **ppDevices = NULL;

    // Create an attribute store to specify the enumeration parameters.
    HRESULT hr = MFCreateAttributes(&pAttributes, 1);
    if (FAILED(hr))
    {
        goto done;
    }

    // Source type: video capture devices
    hr = pAttributes->SetGUID(
        MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, 
        MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
        );
    if (FAILED(hr))
    {
        goto done;
    }

    // Enumerate devices.
    UINT32 count;
    hr = MFEnumDeviceSources(pAttributes, &ppDevices, &count);
    if (FAILED(hr))
    {
        goto done;
    }

    if (count == 0)
    {
        hr = E_FAIL;
        goto done;
    }

    // Create the media source object.
    hr = ppDevices[0]->ActivateObject(IID_PPV_ARGS(&pSource));
    if (FAILED(hr))
    {
        goto done;
    }

    *ppSource = pSource;
    (*ppSource)->AddRef();

done:
    SafeRelease(&pAttributes);

    for (DWORD i = 0; i < count; i++)
    {
        SafeRelease(&ppDevices[i]);
    }
    CoTaskMemFree(ppDevices);
    SafeRelease(&pSource);
    return hr;
}

建立媒體來源之後,請釋放介面指標,並釋放陣列的記憶體:

    SafeRelease(&pAttributes);

    for (DWORD i = 0; i < count; i++)
    {
        SafeRelease(&ppDevices[i]);
    }
    CoTaskMemFree(ppDevices);

視訊