Advanced Sound using DirectX7

 

To start off, go to Project, References…

Check off DirectX7 for Visual Basic Type Library.

 

 

Next, make a module and add the following:

 

Dim DirectX As New DirectX7

Dim DS As DirectSound

 

For each sound you want, declare a DirectSoundBuffer. Here we have three different sounds:

 

Dim earlySound As DirectSoundBuffer

Dim lateSound As DirectSoundBuffer

Dim pureSound As DirectSoundBuffer

 

 

The following function loads all the sound files into memory (the “load sounds” part needs to be modified depending on how many sounds you have).

Make sure the form you’re playing sounds from is specified in the DS.SetCooperativeLevel line. Here my form was frmMain, yours is probably different.

 

 

Public Sub LoadWavFileLists()

   

    Dim bufferDesc As DSBUFFERDESC

    Dim waveFormat As WAVEFORMATEX

    bufferDesc.lFlags = DSBCAPS_CTRLFREQUENCY Or DSBCAPS_CTRLPAN Or DSBCAPS_CTRLVOLUME Or DSBCAPS_STATIC

   

    waveFormat.nFormatTag = WAVE_FORMAT_PCM

    waveFormat.nChannels = 2    '2 channels

    waveFormat.lSamplesPerSec = 22050 '22 hz (i think), only change this if you understand hertz etc.......

    waveFormat.nBitsPerSample = 16  '16 bit rather than 8 bit (Better Quality)

    waveFormat.nBlockAlign = waveFormat.nBitsPerSample / 8 * waveFormat.nChannels

    waveFormat.lAvgBytesPerSec = waveFormat.lSamplesPerSec * waveFormat.nBlockAlign

   

    Set DS = DirectX.DirectSoundCreate("")

   

'This checks for any errors, if there are no 'errors the user has got DX7 and a functional sound card

    If Err.Number <> 0 Then

        MsgBox "Unable to start DirectSound. Check to see that your sound card is properly installed"

        End

    End If

   

' replace frmMain with your form!

    DS.SetCooperativeLevel frmMain.hWnd, DSSCL_PRIORITY

 

 

 

    'load sounds – replace with your own sounds!

    'the first argument is the filename of the sound file

    Set earlySound = DS.CreateSoundBufferFromFile("early.wav", bufferDesc, waveFormat)

    Set lateSound = DS.CreateSoundBufferFromFile("silence_6_seconds.wav", bufferDesc, waveFormat)

    Set pureSound = DS.CreateSoundBufferFromFile("pure.wav", bufferDesc, waveFormat)

       

End Sub

 

 

Now you have access to all the fancy DirectX methods like .SetPan() and .SetVolume() that each buffer can set individually.

For instance, to pan the pure sound all the way to the right channel, and the late sound to the left:

 

Const FULL_RIGHT = 10000

Const FULL_LEFT = -10000

 

pureSound.SetPan FULL_RIGHT

lateSound.SetPan FULL_LEFT

 

 

I find it easier to make a function for each sound subroutine, like the following:

 

 

Public Sub PlayEarlySound()

 

    earlySound.Play DSBPLAY_DEFAULT

 

End Sub

 

Public Sub PlayLateSound()

 

    lateSound.Play DSBPLAY_DEFAULT

 

End Sub

 

Public Sub PlayPureSound()

 

    pureSound.Play DSBPLAY_DEFAULT

 

End Sub