Archived

This topic is now archived and is closed to further replies.

brekehan

DAudio8 and Game Sounds

Recommended Posts

Hiyas, I am trying to put together all the components I need to write a few little games to get started. I was going over a DirectAudio tutorial and came up with this code attached below. I was wondering though, surely I should not load a sound everytime I want to play it. Can I just leave it in my segment object? Also if I have a meriad of sounds in my game should I make a new segment for each sound perhaps an array of them and load them once? What is the best strategy for loading sound resources that are going to be used throughout the program? And how do I make it so that my sound is included in the .exe instead of loaded from a .wav so that everyone does not rip off my cool effects and music? Are there any more resources on the web that give a more thorough guide to DirectAudio and practical use for games? Thanx, Christopher Forgive the word wrapping would take forever to make it look pretty here
  

// INCLUDES ////////////////////////////////////////////////////////

#define WIN32_LEAN_AND_MEAN    // Just say no to MFC!


#include <windows.h>           // Include all the windows headers
#include <Dmusici.h>           // DirectMusic


#include "dxutil.h"            // DirectX utility functions
     

// DEFINES /////////////////////////////////////////////////////////

#define APP_NAME "DirectAudio Demo"      // Name of the window and menu


#define SOUNDERROR_MUSICLOADER      0x8500001
#define SOUNDERROR_MUSICPERFORMANCE 0x8500002
#define SOUNDERROR_INITAUDIO        0x8500003
#define SOUNDERROR_PATH             0x8500004
#define SOUNDERROR_VOLUME           0x8500005
#define SOUNDERROR_LOAD             0x8500006
#define SOUNDERROR_DOWNLOAD         0x8500007
#define SOUNDERROR_NOSEGMENT        0x8500008
#define SOUNDERROR_PLAYFAIL         0x8500009

// GLOBALS ///////////

HWND main_window;                     // Handle to the main window


IDirectMusicLoader8        *pLoader      =NULL;
IDirectMusicPerformance8   *pPerformance =NULL;
IDirectMusicSegment8       *pSound       =NULL;

//PROTOTYPES////////////////////////////////////////////////////////

LRESULT CALLBACK WindowProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam);

HRESULT InitDirectAudio(HWND hWnd);
HRESULT LoadSound(char *filename);
HRESULT PlaySound(IDirectMusicSegment8 *pSegment);
void    CleanupDirectAudio();

//---------------------------------------------------------------------

// WinMain

//---------------------------------------------------------------------

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hprevinstance,
				   LPSTR lpcmdline,int cmdshow)
{
	WNDCLASSEX winclass;    // This holds the window class we create

	MSG        msg;         // Generic message


	// First fill in the windows class structure

	winclass.cbSize         =sizeof(WNDCLASSEX);
	winclass.style          =CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
	winclass.lpfnWndProc    =WindowProc;
	winclass.cbClsExtra     =0;
	winclass.cbWndExtra     =0;
	winclass.hInstance      =hInstance;
	winclass.hIcon          =LoadIcon(NULL,IDI_APPLICATION);
	winclass.hCursor        =LoadCursor(NULL,IDC_ARROW);
	winclass.hbrBackground  =(HBRUSH)GetStockObject(BLACK_BRUSH);
	winclass.lpszMenuName   =NULL;
	winclass.lpszClassName  =APP_NAME;
	winclass.hIconSm        =LoadIcon(NULL,IDI_APPLICATION);

	// Register the new window class

	if(!RegisterClassEx(&winclass))
		return(0);

	// Create the window

	if(!(main_window=CreateWindowEx(WS_EX_TOPMOST,                 // Extended Style

		                     APP_NAME,                             // Class

		                     APP_NAME,                             // Title

                             WS_OVERLAPPEDWINDOW | WS_VISIBLE,     // Flags

		                     0,0,                                  // Initial x,y

		                     640,480,                              // Initial width,height

                             NULL,                                 // Handle to parent

		                     NULL,                                 // Handle to menu

		                     hInstance,                            // Instance of this application

		                     NULL)))                               // Extra creation parms

		return 0;

	ShowWindow(main_window,SHOW_FULLSCREEN);
	UpdateWindow(main_window);

	// Initialize

		// Direct Audio

	if(S_OK!=InitDirectAudio(main_window))
	{
		MessageBox(main_window,"DirectAudio Error",
			"Unable to Initialize DirectAudio",MB_ICONERROR);
		CleanupDirectAudio();
		return 1;
	}

	
	// Enter main event loop

	while(msg.message!=WM_QUIT)
	{
		// Test if there is a message in que, if so get it

		if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{
			// Translate any accelerator keys

			TranslateMessage(&msg);

			// Send the message to window proc

			DispatchMessage(&msg);
		}

		// Main processing loop

		else
		{
			// Load a sound

			if(S_OK!=LoadSound("testsound.wav"))
			{
				MessageBox(main_window,"DirectAudio Error",
				"Unable to load media sample.",MB_ICONERROR);
				CleanupDirectAudio();
				return 1;
			}

			// Play the sound

			PlaySound(pSound);
			
			// Wait 1/2 second

			Sleep(1000);
		}
	}

	// Shutdown

		
		// Window

	UnregisterClass(APP_NAME,hInstance);

	// Return to windows

	return(msg.wParam);
}

//----------------------------------------------------------------------

// Windows Message Handler

//----------------------------------------------------------------------

LRESULT CALLBACK WindowProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
	// What is the message? 

	switch(msg)
	{	

	case WM_DESTROY:
		PostQuitMessage(0);
		return 0; 
	
	default:
		break;

    } 

	// Process any messages that we didn't take care of 

	return (DefWindowProc(hWnd, msg, wParam, lParam));
} 

//----------------------------------------------------------------------

// Initialize Direct Audio

//----------------------------------------------------------------------

HRESULT InitDirectAudio(HWND hWnd)
{
	IDirectMusicAudioPath8  *path;

	// Initialize COM

	CoInitialize(NULL);

	// Create the Loader

	if(FAILED(CoCreateInstance(CLSID_DirectMusicLoader,NULL,
		CLSCTX_INPROC,IID_IDirectMusicLoader8,(void**)&pLoader)))
		return SOUNDERROR_MUSICLOADER;

	// Create the Performance

	if(FAILED(CoCreateInstance(CLSID_DirectMusicPerformance,NULL,
		CLSCTX_INPROC,IID_IDirectMusicPerformance8,(void**)&pPerformance)))
		return SOUNDERROR_MUSICPERFORMANCE;

	// Initialize the Audio

	if(FAILED(pPerformance->InitAudio(NULL,NULL,main_window,
		DMUS_APATH_DYNAMIC_STEREO,4,DMUS_AUDIOF_ALL,NULL)))
		return SOUNDERROR_INITAUDIO;
	
	// Get the Default Path

	if(FAILED(pPerformance->GetDefaultAudioPath(&path)))
		return SOUNDERROR_PATH;

	// Set the Default Volume

	if(FAILED(path->SetVolume(0,0)))
		return SOUNDERROR_VOLUME;

	return S_OK;
}

//----------------------------------------------------------------------

// Load a sound

//----------------------------------------------------------------------

HRESULT LoadSound(char *filename)
{
	WCHAR wstrFileName[256];

	// Convert the filename to wide character format

	DXUtil_ConvertGenericStringToWide(wstrFileName,filename);

	// Make Sure Audio Is Initialized

	if(!pLoader)
		return SOUNDERROR_MUSICLOADER;
	if(!pPerformance)
		return SOUNDERROR_MUSICPERFORMANCE;

	// Clean-up sound if it already exists

	if(pSound)
	{
		pSound->Unload(pPerformance);
		pSound->Release();
		pSound=NULL;
	}

	// Load the sound from a file

	if(FAILED(pLoader->LoadObjectFromFile(CLSID_DirectMusicSegment,
		IID_IDirectMusicSegment8,wstrFileName,(LPVOID*)&pSound)))
		return SOUNDERROR_LOAD;

	// Download the data

	if(FAILED(pSound->Download(pPerformance)))
		return SOUNDERROR_DOWNLOAD;

	return S_OK;
}

//----------------------------------------------------------------------

// Play a sound

//----------------------------------------------------------------------

HRESULT PlaySound(IDirectMusicSegment8 *pSegment)
{
	// Make sure there is a performance object present

	if(!pPerformance)
		return SOUNDERROR_MUSICPERFORMANCE;
	if(!pSegment)
		return SOUNDERROR_NOSEGMENT;

	// Play the sound segment

	if(FAILED(pPerformance->PlaySegmentEx(pSegment,NULL,NULL,
		DMUS_SEGF_DEFAULT | DMUS_SEGF_SECONDARY,0,NULL,NULL,NULL)))
		return SOUNDERROR_PLAYFAIL;

	return S_OK;
}

//----------------------------------------------------------------------

// Clean-up Direct Audio

//----------------------------------------------------------------------

void CleanupDirectAudio()
{
	// Clear the sound

	if(pSound)
	{
		pSound->Unload(pPerformance);
		pSound->Release();
		pSound=NULL;
	}

	// Clear the Loader

	if(pLoader)
	{
		pLoader->Release();
		pLoader=NULL;
	}

	// Clear the Performer

	if(pPerformance)
	{
		pPerformance->Release();
		pPerformance=NULL;
	}

	// Shutdown COM

	CoUninitialize();
}    

  
*Edit - Added source tags -Jim [edited by - Jim Adams on September 3, 2002 9:37:42 AM]

Share this post


Link to post
Share on other sites
make one class that has the performance and loader. and make another class that takes in the first class and uses the performance to make segments. have many instances of the second class. but only one instance of the first class. so u''ll make second classes for all the different sounds u need and use them



"We call em ''natural disasters'' but ''he'' (or she?) calls them memory leaks!!"
Al
**MY HQ**

Share this post


Link to post
Share on other sites