首先要声明三个接口,用于声音的播放。
如果是视频还需加上:IVideoWindow
IGraphBuilder* g_pGraphBuilder=NULL;
IMediaControl* g_pMediaControl=NULL;
IMediaPosition* g_pMediaPosition=NULL;
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
然后在初始化函数中,
// 初始COM
CoInitialize(NULL);
// 创建IGraphBuilder接口对象
CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void**)&g_pGraphBuilder);
// 创建IMediaControl和IMediaPosition对象
g_pGraphBuilder->QueryInterface(IID_IMediaControl, (void**)&g_pMediaControl);
g_pGraphBuilder->QueryInterface(IID_IMediaPosition, (void**)&g_pMediaPosition);
// 加载MP3数据
g_pGraphBuilder->RenderFile(L"Mandy.mp3", NULL);
接着在渲染函数中播放声音
if (::GetAsyncKeyState(VK_SPACE) & 0x8000f)
g_pMediaControl->Run(); // 播放
if (::GetAsyncKeyState('P') & 0x8000f)
g_pMediaControl->Pause(); // 暂停
if (::GetAsyncKeyState('S') & 0x8000f) // 停止
g_pMediaControl->Stop(), g_pMediaPosition->put_CurrentPosition(0);
if (::GetAsyncKeyState(VK_LEFT) & 0x8000f) // 快退
{
REFTIME refPosition = 0.0;
g_pMediaPosition->get_CurrentPosition(&refPosition);
refPosition -= 1.0;
if (refPosition <= 0.0) refPosition = 0.0;
g_pMediaPosition->put_CurrentPosition(refPosition);
}
if (::GetAsyncKeyState(VK_RIGHT) & 0x8000f) // 快进
{
REFTIME refPosition = 0.0;
REFTIME refDuration = 0.0;
g_pMediaPosition->get_CurrentPosition(&refPosition);
g_pMediaPosition->get_Duration(&refDuration);// 总长度
refPosition += 1.0;
if (refPosition >= refDuration) refPosition = refDuration;
g_pMediaPosition->put_CurrentPosition(refPosition);
}
最后释放掉相关接口
g_pMediaControl->Stop();
SAFE_RELEASE(g_pGraphBuilder);
SAFE_RELEASE(g_pMediaControl);
SAFE_RELEASE(g_pMediaPosition);
SAFE_RELEASE(g_pd3dDevice);
CoUninitialize();