Game Development Reference
In-Depth Information
try
{
// Create our DirectSound object.
m_DirectSound = new DirectSound();
}
catch (DirectSoundException dsException)
{
return;
}
Inside the
catch
block, we input our code to handle the error condition. In this case,
we just make the constructor return without finishing initialization. This prevents the
program from crashing, but it still won't work, right? (It won't have sound.) So, basic-
ally, if the initialization of the
DirectSound
object fails, the code in the
catch
block
will run.
Error handling is extremely important in real-world applications, so don't forget about
it!
Next, we set the cooperative level. The cooperative level determines the extent to
which the system allows this program to use the device. This is because Windows
is a multitasking environment and therefore multiple applications could be using the
sound device at the same time. Cooperative level is the way the system makes sure
that we don't have two programs trying to use the device at exactly the same time,
as this can cause problems. As you can see, we set the cooperative level to
Coop-
erativeLevel.Priority
here. This is usually what you'll want to set it to if your
application is a game.
The next three lines of code create our
PrimarySoundBuffer
object and give it
the
BufferFlags.PrimaryBuffer
flag.
The next chunk of code sets up our
SecondarySoundBuffer
object. It starts with
a
using
block that creates a
WaveStream
object that is using our sound file. Inside
the
using
block, we create a
SoundBufferDescription
object that we will use
to specify the properties of our
SecondarySoundBuffer
object when we create
it. We set the
SizeInBytes
property to the size of our wave file. Then, we set the
Flags
property to have the
BufferFlags.ControlVolume
flag. Having this flag