How to Find the Duration of a Media File

To find the duration of a media file, perform the following steps:

  1. Use the Source Resolver to create a media source that can parse the media file.
  2. Call IMFMediaSource::CreatePresentationDescriptor on the media source. This method returns presentation descriptor that describes the contents of the media file.
  3. Query the presentation descriptor for the MF_PD_DURATION attribute by calling the IMFAttributes::GetUINT64 method. The value of the attribute, if present, is the file duration in 100-nanosecond units.
HRESULT GetSourceDuration(IMFMediaSource *pSource, MFTIME *pDuration)
{
    *pDuration = 0;

    IMFPresentationDescriptor *pPD = NULL;

    HRESULT hr = pSource->CreatePresentationDescriptor(&pPD);
    if (SUCCEEDED(hr))
    {
        hr = pPD->GetUINT64(MF_PD_DURATION, (UINT64*)pDuration);
        pPD->Release();
    }
    return hr;
}

Audio/Video Playback