Writing a Square Wave to DirectSound
DirectSound is Object Oriented
DirectSound in an object-oriented API. What does that mean? Casey starts this episode with a discussion of "method" dispatch through vtables, and why c++ virtual calls are costly.
Reviewing DirectSound Inititalization
The basic process for initializing DirectSound is as follows:
- Load the Library -
LoadLibrary
("dsound.dll")
- Create a DirectSound object -
DirectSoundCreate()
- Set the Cooperative Level -
IDirectSound8::SetCooperativeLevel()
- "Create" a primary buffer -
IDirectSound8::CreateSoundBuffer()
- Create a secondary buffer
- Tell DirectSound to start playing the secondary buffer -
IDirectSoundBuffer8::Play()
Playing sounds
Audio is a complicated topic, and we start with a discussion of audio "waveforms" and how PCM audio data is encoded in memory.
- A square wave oscillates between "full-positive" to "full-negative" every half period
- A Stereo (2-channel) 16-bit PCM audio buffer is arranged as an array of signed int16 values in (left channel value, right channel value) pairs
- A "sample" sometimes refers to the values for all channels in a sampling period, and sometimes a value for a single channel. Be careful.
The procedure for writing sound data into a buffer is as follows
- Figure out where in the buffer you want to start writing, and how much data you want to write
- Its useful to look at the play cursor -
IDirectSoundBuffer8::GetCurrentPosition()
- Its useful to look at the play cursor -
- Acquire a lock on the buffer -
IDirectSoundBuffer8::Lock()
- Because we are working with a circular buffer, this call will return 1 or 2 writable regions
- Write the samples to the buffer
- Unlock the regions -
IDirectSoundBuffer8::Unlock()
A note on audio latency
Audio latency is determined not by the size of the buffer, but by how far ahead of the PlayCursor you write. The optimal amount of latency is the amount that will cause this frame's audio to coincide with the display of this frame's image. On most platforms, it is very difficult to ascertain the proper amount of latency. It's an unsolved problem, and games with need precise AV sync (like Guitar Hero) go to some lengths to achieve it.