Step 3: Open a Media File

This topic is step 3 of the tutorial How to Play Media Files with Media Foundation. The complete code is shown in the topic Media Session Playback Example.

The CPlayer::OpenURL method opens a media file from a URL.

//  Open a URL for playback.
HRESULT CPlayer::OpenURL(const WCHAR *sURL)
{
    // 1. Create a new media session.
    // 2. Create the media source.
    // 3. Create the topology.
    // 4. Queue the topology [asynchronous]
    // 5. Start playback [asynchronous - does not happen in this method.]

    IMFTopology *pTopology = NULL;
    IMFPresentationDescriptor* pSourcePD = NULL;

    // Create the media session.
    HRESULT hr = CreateSession();
    if (FAILED(hr))
    {
        goto done;
    }

    // Create the media source.
    hr = CreateMediaSource(sURL, &m_pSource);
    if (FAILED(hr))
    {
        goto done;
    }

    // Create the presentation descriptor for the media source.
    hr = m_pSource->CreatePresentationDescriptor(&pSourcePD);
    if (FAILED(hr))
    {
        goto done;
    }

    // Create a partial topology.
    hr = CreatePlaybackTopology(m_pSource, pSourcePD, m_hwndVideo, &pTopology);
    if (FAILED(hr))
    {
        goto done;
    }

    // Set the topology on the media session.
    hr = m_pSession->SetTopology(0, pTopology);
    if (FAILED(hr))
    {
        goto done;
    }

    m_state = OpenPending;

    // If SetTopology succeeds, the media session will queue an 
    // MESessionTopologySet event.

done:
    if (FAILED(hr))
    {
        m_state = Closed;
    }

    SafeRelease(&pSourcePD);
    SafeRelease(&pTopology);
    return hr;
}

This method performs the following steps:

  1. Calls CPlayer::CreateSession to create a new instance of the Media Session. See Step 4: Create the Media Session.
  2. Creates a media source from the URL. The complete code for this step is shown in the topic Using the Source Resolver.
  3. Calls IMFMediaSource::CreatePresentationDescriptor to get the media source's presentation descriptor. The presentation descriptor describes each streams in the source file.
  4. Creates the playback topology. Code for this step is shown in the topic Creating Playback Topologies.
  5. Calls IMFMediaSession::SetTopology to set the topology on the Media Session.

The SetTopology method completes asynchronously. When it completes, the CPlayer object's IMFAsyncCallback::Invoke method is called; see Step 5: Handle Media Session Events.

Next: Step 4: Create the Media Session

Audio/Video Playback

How to Play Media Files with Media Foundation