Game Development Reference
In-Depth Information
Note
Remember that the
using
block will automatically dispose of our
WaveStream
when program execution reaches the end of the
using
block, and that
using
blocks only work like this with types that implement the
IDisposable
interface.
The first four lines of code inside the
using
block set up our audio buffer. The first
one creates the
AudioBuffer
object. The second line sets the buffer's
AudioData
property to our
WaveStream
object to get the audio data from the
.wav
file and into
our audio buffer. The third line sets the buffer's
AudioBytes
property to the length
of the
.wav
file, so the buffer knows how much data we have shoved into it.
The next line of code tells XAudio2 that we want to loop this sound. This is done
by setting the
LoopCount
property to
XAudio2.LoopInfinite
. The
LoopCount
property sets how many times we want to loop the sound. You can set the start po-
sition for the loop and the end position via the
AudioBuffer
's
BeginLoop
and
EndLoop
properties. This is not necessary if your audio file already has looping data
in it. In this case these properties are already set for us based on the data from the
file. Note that the
AudioBuffer
class also has the
PlayBegin
and
PlayLength
properties that let you set the portion of the sound that you wish to play. These prop-
erties are set to the beginning and end of the sound file by default.
Note
The
BufferFlags
enumeration wejust usedisnot the sameoneweusedwhen
wewereworkingwithDirectSound. TheDirectSound enumeration forbuffer flags
is
SlimDX.DirectSound.BufferFlags
, while the XAudio2 enumeration for
buffer flags is
SlimDX.XAudio2.BufferFlags
.
The last three lines of code set up our
SourceVoice
object. This object is used to
submit our audio data to the
MasteringVoice
object so that we can play it. So, the
first of these three lines creates the
SourceVoice
object. The second line submits
the audio data from our
AudioBuffer
, so that we can play it, and the last line plays
our sound.