步驟 2:建立 CPlayer 物件

本主題是 如何使用媒體基礎播放媒體檔案教學課程的步驟 2。 完整的程式碼會顯示在 媒體會話播放範例主題中。

若要建立 類別的 CPlayer 實例,應用程式會呼叫靜態 CPlayer::CreateInstance 方法。 此方法採用下列參數:

  • hVideo 會指定要顯示視訊的視窗。
  • hEvent 會指定要接收事件的視窗。 這兩個視窗控制碼的傳遞相同控制碼是有效的。
  • ppPlayer 會收到新 CPlayer 實例的指標。

下列程式碼顯示 CreateInstance 方法:

//  Static class method to create the CPlayer object.

HRESULT CPlayer::CreateInstance(
    HWND hVideo,                  // Video window.
    HWND hEvent,                  // Window to receive notifications.
    CPlayer **ppPlayer)           // Receives a pointer to the CPlayer object.
{
    if (ppPlayer == NULL)
    {
        return E_POINTER;
    }

    CPlayer *pPlayer = new (std::nothrow) CPlayer(hVideo, hEvent);
    if (pPlayer == NULL)
    {
        return E_OUTOFMEMORY;
    }

    HRESULT hr = pPlayer->Initialize();
    if (SUCCEEDED(hr))
    {
        *ppPlayer = pPlayer;
    }
    else
    {
        pPlayer->Release();
    }
    return hr;
}

HRESULT CPlayer::Initialize()
{
    // Start up Media Foundation platform.
    HRESULT hr = MFStartup(MF_VERSION);
    if (SUCCEEDED(hr))
    {
        m_hCloseEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
        if (m_hCloseEvent == NULL)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
        }
    }
    return hr;
}

下列程式碼顯示建 CPlayer 構函式:

CPlayer::CPlayer(HWND hVideo, HWND hEvent) : 
    m_pSession(NULL),
    m_pSource(NULL),
    m_pVideoDisplay(NULL),
    m_hwndVideo(hVideo),
    m_hwndEvent(hEvent),
    m_state(Closed),
    m_hCloseEvent(NULL),
    m_nRefCount(1)
{
}

建構函式會執行下列動作:

  1. 呼叫 MFStartup 以初始化 Media Foundation 平臺。
  2. 建立自動重設事件。 關閉媒體會話時,會使用此事件;請參閱 步驟 7:關閉媒體會話

解構函式會關閉媒體會話,如 步驟 7:關閉媒體會話中所述。

CPlayer::~CPlayer()
{
    assert(m_pSession == NULL);  
    // If FALSE, the app did not call Shutdown().

    // When CPlayer calls IMediaEventGenerator::BeginGetEvent on the
    // media session, it causes the media session to hold a reference 
    // count on the CPlayer. 
    
    // This creates a circular reference count between CPlayer and the 
    // media session. Calling Shutdown breaks the circular reference 
    // count.

    // If CreateInstance fails, the application will not call 
    // Shutdown. To handle that case, call Shutdown in the destructor. 

    Shutdown();
}

請注意,建構函式和解構函式都是受保護的類別方法。 應用程式會使用靜態 CreateInstance 方法建立 物件。 它會藉由呼叫 IUnknown::Release來終結物件,而不是明確使用 delete

下一 步:步驟 3:開啟媒體檔案

音訊/視訊播放

如何使用媒體基礎播放媒體檔案