How to Play Media Files with Media Foundation
This tutorial shows how to play media files using the Media Session object.
Before reading this topic, you should be familiar with the following Media Foundation concepts:
The following objects are used to play a media file with the Media Session:
- A media source is an object that parses a media file or other source of media data. The media source creates stream objects for each audio or video stream in the file. Decoders convert encoded media data into uncompressed video and audio.
- The Source Resolver creates a media source from a URL.
- The Enhanced Video Renderer (EVR) renders video to the screen.
- The Streaming Audio Renderer (SAR) renders audio to a speaker or other audio output device.
- A topology defines the flow of data from the media source to the EVR and SAR.
- The Media Session controls the data flow and sends status events to the application. The following diagram illustrates this process.
The following is a general outline of the steps needed to play a media file using the Media Session:
- Call the MFStartup function to initialize the Media Foundation platform.
- Call MFCreateMediaSession to create a new instance of the Media Session.
- Use the source resolver to create a media source. For more information, see Using the Source Resolver.
- Create a topology that connects the media source to the EVR and SAR. In this step, the application creates a partial topology that does not include the decoders. For more information, see Creating Playback Topologies.
- Call IMFMediaSession::SetTopology to set the topology on the Media Session.
- Use the IMFMediaEventGenerator interface to get events from the Media Session.
- Call IMFMediaSession::Start to start playback. After playback starts, you can pause it by calling IMFMediaSession::Pause, or stop it by calling IMFMediaSession::Stop.
When the application exits, release resources:
- Call IMFMediaSession::Close to close the Media Session. This method is asynchronous. When it completes, the Media Session sends an MESessionClosed event. Then it is safe to perform the remaining steps.
- Call IMFMediaSource::Shutdown to shut down the media source.
- Call IMFMediaSession::Shutdown to shut down the Media Session.
- Call MFShutdown to shut down the Media Foundation platform.
The following sections show a complete code example:
- Step 1: Declare the CPlayer Class
- Step 2: Create the CPlayer Object
- Step 3: Open a Media File
- Step 4: Create the Media Session
- Step 5: Handle Media Session Events
- Step 6: Control Playback
- Step 7: Shut Down the Media Session
- Media Session Playback Example