How to Play a File Clip

[The feature associated with this page, MFPlay, is a legacy feature. It has been superseded by MediaPlayer and IMFMediaEngine. Those features have been optimized for Windows 10 and Windows 11. Microsoft strongly recommends that new code use MediaPlayer and IMFMediaEngine instead of DirectShow, when possible. Microsoft suggests that existing code that uses the legacy APIs be rewritten to use the new APIs if possible.]

This topic describes how to play a segment of a media file in MFPlay, by setting the start and stop times for playback.

To Play a File Clip

  1. Call IMFPMediaPlayer::CreateMediaItemFromURL or IMFPMediaPlayer::CreateMediaItemFromObject to create a media item for the file.
  2. Optionally, get the total duration of the file, as described in How to Get the Playback Duration.
  3. Call IMFPMediaItem::SetStartStopPosition to set the start and stop times. The stop time must not exceed the file duration.
  4. Call IMFPMediaPlayer::SetMediaItem to start playback.

The following example uses the blocking version of CreateMediaItemFromURL. If the non-blocking version is used, the code that appears after CreateMediaItemFromURL should be placed in the handler for the MFP_EVENT_TYPE_MEDIAITEM_CREATED event. For more information about events in MFPlay, see Receiving Events From the Player.

To get the file duration, this example calls the GetPlaybackDuration function shown in the topic How to Get the Playback Duration.

HRESULT PlayMediaClip(
    IMFPMediaPlayer *pPlayer,
    PCWSTR pszURL,
    LONGLONG    hnsStart,
    LONGLONG    hnsEnd
    )
{
    IMFPMediaItem *pItem = NULL;
    PROPVARIANT varStart, varEnd;

    ULONGLONG hnsDuration = 0;

    HRESULT hr = pPlayer->CreateMediaItemFromURL(pszURL, TRUE, 0, &pItem);
    if (FAILED(hr))
    {
        goto done;
    }

    hr = GetPlaybackDuration(pItem, &hnsDuration);
    if (FAILED(hr))
    {
        goto done;
    }

    if ((ULONGLONG)hnsEnd > hnsDuration)
    {
        hnsEnd = hnsDuration;
    }

    hr = InitPropVariantFromInt64(hnsStart, &varStart);
    if (FAILED(hr))
    {
        goto done;
    }

    hr = InitPropVariantFromInt64(hnsEnd, &varEnd);
    if (FAILED(hr))
    {
        goto done;
    }

    hr = pItem->SetStartStopPosition(
        &MFP_POSITIONTYPE_100NS,
        &varStart,
        &MFP_POSITIONTYPE_100NS,
        &varEnd
        );
    if (FAILED(hr))
    {
        goto done;
    }

    hr = pPlayer->SetMediaItem(pItem);

done:
    SafeRelease(&pItem);
    return hr;
}

Requirements

MFPlay requires Windows 7.

Using MFPlay for Audio/Video Playback