Music.cpp
上传用户:cjwanglu
上传日期:2013-07-10
资源大小:4744k
文件大小:3k
源码类别:

游戏

开发平台:

Visual C++

  1. #include "stdafx.h"
  2. #include "Music.h"
  3. CMusic::CMusic(HWND hWnd)
  4. {
  5.         m_pDirectAudioPerformance = NULL;
  6. m_pDirectAudioLoader = NULL;
  7. m_pSegment = NULL;
  8. m_pGraph = NULL;
  9. m_pMediaControl = NULL;
  10. m_pMediaPosition = NULL;
  11. m_enumFormat = Unknown;
  12. CoInitialize(NULL);
  13. //Create the DirectAudio performance object
  14. CoCreateInstance(CLSID_DirectMusicPerformance, NULL, CLSCTX_INPROC, 
  15. IID_IDirectMusicPerformance8, (void**) &m_pDirectAudioPerformance);
  16. //Create the DirectAudio loader object
  17. CoCreateInstance(CLSID_DirectMusicLoader, NULL, CLSCTX_INPROC, 
  18. IID_IDirectMusicLoader8, (void**) &m_pDirectAudioLoader);
  19. //Initialise the performance object
  20. m_pDirectAudioPerformance->InitAudio(NULL, NULL, hWnd, DMUS_APATH_SHARED_STEREOPLUSREVERB,
  21.  64, DMUS_AUDIOF_ALL, NULL);
  22. GetCurrentDirectory(MAX_PATH, strSoundPath);
  23. MultiByteToWideChar(CP_ACP, 0, strSoundPath, -1, wstrSoundPath, MAX_PATH);
  24. m_pDirectAudioLoader->SetSearchDirectory(GUID_DirectMusicAllTypes, wstrSoundPath, FALSE);
  25.     CoCreateInstance(CLSID_FilterGraph, NULL,
  26.             CLSCTX_INPROC, IID_IGraphBuilder, (void**)&m_pGraph);
  27. m_pGraph->QueryInterface(IID_IMediaControl, (void**)&m_pMediaControl);
  28. m_pGraph->QueryInterface(IID_IMediaPosition, (void**)&m_pMediaPosition);
  29. }
  30. CMusic::~CMusic()
  31. {
  32.         m_pDirectAudioPerformance->Stop(NULL, NULL, 0, 0);
  33. m_pDirectAudioPerformance->CloseDown();
  34. //SafeRRelease(m_pDirectAudioLoader);
  35. //SafeRRelease(m_pDirectAudioPerformance);
  36. m_pDirectAudioLoader->Release();
  37. m_pDirectAudioPerformance->Release();
  38. CoUninitialize();
  39. }
  40. void CMusic::Play(int t,LPSTR pStr)
  41. {
  42. switch(t)
  43. {
  44. case 0:
  45.             m_enumFormat = WavMidi;
  46. //初始化WAV文件,将文件名转换为unicode
  47. MultiByteToWideChar(CP_ACP, 0, "2-02 Ahead on Our Way Midi.mid", -1, wstrSoundPath, MAX_PATH);
  48. //加载声音
  49. m_pDirectAudioLoader->LoadObjectFromFile(CLSID_DirectMusicSegment, IID_IDirectMusicSegment8,
  50.  wstrSoundPath, (void**) &m_pSegment);
  51. m_pSegment->Download(m_pDirectAudioPerformance);
  52. m_pSegment->SetRepeats(-1);  //这里可以设置循环次数,-1为循环播放
  53. m_pDirectAudioPerformance->PlaySegmentEx(m_pSegment, NULL, NULL, 0, 0, NULL, NULL, NULL);
  54. break;
  55. case 1:
  56.     m_enumFormat = MP3;
  57. //初始化MP3文件,得到MP3文件所在的目录
  58. GetCurrentDirectory(MAX_PATH, strSoundPath);
  59. strcat(strSoundPath, pStr);//\Love.mp3
  60. //将文件名转换为unicode
  61. MultiByteToWideChar(CP_ACP, 0, strSoundPath, -1, wstrSoundPath, MAX_PATH);
  62. m_pGraph->RenderFile(wstrSoundPath, NULL);
  63. m_pMediaPosition->put_CurrentPosition(0);
  64. m_pMediaControl->Run();
  65. break;
  66. }
  67. }