Basics of setting up and getting Direct Sound going (in C)


#include <dsound.h>

extern HWND hMainWnd;  //handle to the window from the main windows program
static LPDIRECTSOUND lpDS; //pointer to the directsound object

/* This function will initialize Direct Sound */
/* it returns TRUE if it was successful or FALSE otherwise */

BOOL Sound_Init(void)
{
    if (DS_OK==DirectSoundCreate(NULL,&lpDS,NULL)) //create direct sound object
    {
        //ok, DirectSound Object created, let's take control now...
        if (DS_OK==IDirectSound_SetCooperativeLevel(lpDS, hMainWnd, DSSCL_EXCLUSIVE))
        {
            //MessageBox(hMainWnd,"Cooperative Level Succefully Set!","Good!!",MB_OK);
            return TRUE;
        }
        else //SetCoop was unsuccessful, let's give up control
        {
            IDirectSound_Release(lpDS);
            MessageBox(hMainWnd,"Set Cooperative Level didn't Work!","BAD!!",MB_OK);
            return FALSE;
        }
    }
    else  //DSObj creation was unsuccessful
    {
        MessageBox(hMainWnd,"Could Not Create Direct Sound Object","Error!",MB_OK);
        return (FALSE);
    }
}

/*here's a simple function to shut down direct sound when you're done with it */
void Sound_Exit(void)
{
    if (lpDS)
    {
        IDirectSound_Release(lpDS);
    }
    else
    {
        MessageBox(hMainWnd,"Sound was not initialized and cannot Exit!",
                "Error!",MB_OK);
    }
}

There you go... some code to get it going and to shut it down, it should be simple enough to convert to C++ if you want (why would you want to though?) what comes next is adding code to load in a WAVE file (or some other type of sound file), parse it's header, then create a sound buffer that DirectSound can actually play. I have code to do this but, I need to know if anyone is even interested in it before i put forth the effort to edit it and throw it on my web page. So send some E-Mail to npawn@aros.net if you're at all interested in seeing some more Direct Sound code.

Reprinted with permission

Discuss this article in the forums


Date this article was posted to GameDev.net: 7/31/1999
(Note that this date does not necessarily correspond to the date the article was written)

See Also:
DirectX Audio

© 1999-2011 Gamedev.net. All rights reserved. Terms of Use Privacy Policy
Comments? Questions? Feedback? Click here!