www.pudn.com > 3DRPG.rar > Music.cpp
#include "stdafx.h"
#include "Music.h"
CMusic::CMusic(HWND hWnd)
{
m_pDirectAudioPerformance = NULL;
m_pDirectAudioLoader = NULL;
m_pSegment = NULL;
m_pGraph = NULL;
m_pMediaControl = NULL;
m_pMediaPosition = NULL;
m_enumFormat = Unknown;
CoInitialize(NULL);
//Create the DirectAudio performance object
CoCreateInstance(CLSID_DirectMusicPerformance, NULL, CLSCTX_INPROC,
IID_IDirectMusicPerformance8, (void**) &m_pDirectAudioPerformance);
//Create the DirectAudio loader object
CoCreateInstance(CLSID_DirectMusicLoader, NULL, CLSCTX_INPROC,
IID_IDirectMusicLoader8, (void**) &m_pDirectAudioLoader);
//Initialise the performance object
m_pDirectAudioPerformance->InitAudio(NULL, NULL, hWnd, DMUS_APATH_SHARED_STEREOPLUSREVERB,
64, DMUS_AUDIOF_ALL, NULL);
GetCurrentDirectory(MAX_PATH, strSoundPath);
MultiByteToWideChar(CP_ACP, 0, strSoundPath, -1, wstrSoundPath, MAX_PATH);
m_pDirectAudioLoader->SetSearchDirectory(GUID_DirectMusicAllTypes, wstrSoundPath, FALSE);
CoCreateInstance(CLSID_FilterGraph, NULL,
CLSCTX_INPROC, IID_IGraphBuilder, (void**)&m_pGraph);
m_pGraph->QueryInterface(IID_IMediaControl, (void**)&m_pMediaControl);
m_pGraph->QueryInterface(IID_IMediaPosition, (void**)&m_pMediaPosition);
}
CMusic::~CMusic()
{
m_pDirectAudioPerformance->Stop(NULL, NULL, 0, 0);
m_pDirectAudioPerformance->CloseDown();
//SafeRRelease(m_pDirectAudioLoader);
//SafeRRelease(m_pDirectAudioPerformance);
m_pDirectAudioLoader->Release();
m_pDirectAudioPerformance->Release();
CoUninitialize();
}
void CMusic::Play(int t,LPSTR pStr)
{
switch(t)
{
case 0:
m_enumFormat = WavMidi;
//初始化WAV文件,将文件名转换为unicode
MultiByteToWideChar(CP_ACP, 0, "2-02 Ahead on Our Way Midi.mid", -1, wstrSoundPath, MAX_PATH);
//加载声音
m_pDirectAudioLoader->LoadObjectFromFile(CLSID_DirectMusicSegment, IID_IDirectMusicSegment8,
wstrSoundPath, (void**) &m_pSegment);
m_pSegment->Download(m_pDirectAudioPerformance);
m_pSegment->SetRepeats(-1); //这里可以设置循环次数,-1为循环播放
m_pDirectAudioPerformance->PlaySegmentEx(m_pSegment, NULL, NULL, 0, 0, NULL, NULL, NULL);
break;
case 1:
m_enumFormat = MP3;
//初始化MP3文件,得到MP3文件所在的目录
GetCurrentDirectory(MAX_PATH, strSoundPath);
strcat(strSoundPath, pStr);//\\Love.mp3
//将文件名转换为unicode
MultiByteToWideChar(CP_ACP, 0, strSoundPath, -1, wstrSoundPath, MAX_PATH);
m_pGraph->RenderFile(wstrSoundPath, NULL);
m_pMediaPosition->put_CurrentPosition(0);
m_pMediaControl->Run();
break;
}
}