在vc编程中如何添加背景音乐

  今天把游戏背景音乐封装了一下,这个封装基本是参照了DMUtil.h的几个类。

#include “DMUtil.h”
先在类里面申明
CMusicManager* g_pMusicManager;
CMusicSegment* g_pMusicSegment;

构造初始
g_pMusicManager = NULL;
g_pMusicSegment = NULL;

封装的四个函数
void InitMusic(HWND hWnd);          // 初始化
HRESULT LoadSegmentFile( HWND hDlg, TCHAR* strFileName); // 载入音乐文件
void PlayMusic(HWND hDlg, BOOL bLooped);   // 播放,可控制是否循环播放
void StopMusic();               // 停止播放

HRESULT CMyD3DApplication::LoadSegmentFile( HWND hDlg, TCHAR* strFileName )
{
HRESULT hr;
SAFE_Delete( g_pMusicSegment );
// Have the loader collect any garbage now that the old
// segment has been released
g_pMusicManager->CollectGarbage();
// Set the media path based on the file name (something like C:MEDIA)
// to be used as the search directory for finding DirectMusic content
// related to this file.
TCHAR strMediaPath[MAX_PATH];
GetCurrentDirectory(MAX_PATH, strMediaPath);
g_pMusicManager->SetSearchDirectory(strMediaPath);
BOOL bMidiFile = FALSE;
// Load the file into a DirectMusic segment
if( FAILED( g_pMusicManager->CreateSegmentFromFile( &g_pMusicSegment, strFileName,
TRUE, bMidiFile ) ) )
{
MessageBox( NULL, “No find Music sound.”, “”, MB_OK | MB_ICONERROR );
return S_FALSE;
}
return S_OK;
}

void CMyD3DApplication::InitMusic(HWND hWnd)
{
g_pMusicManager = new CMusicManager();
g_pMusicManager->Initialize(m_hWnd );
TCHAR strFileName[MAX_PATH];
strcpy( strFileName, “sample.sgt” );
LoadSegmentFile(m_hWnd, strFileName ) ;
}

void CMyD3DApplication::PlayMusic( HWND hDlg, BOOL bLooped )
{
if( bLooped )
{
// Set the segment to repeat many times
g_pMusicSegment->SetRepeats( DMUS_SEG_REPEAT_INFINITE );
}
else
{
// Set the segment to not repeat
g_pMusicSegment->SetRepeats( 0 );
}

g_pMusicSegment->Play( DMUS_SEGF_BEAT );
}

void CMyD3DApplication::StopMusic()
{
g_pMusicSegment->Stop( DMUS_SEGF_BEAT );
}

就这么简单。四个函数就搞定游戏背景音乐了。

点赞 (0)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Captcha Code