• Using the sndPlaySound function in the previous example requires first
opening a file, then playing the sound. If you want quick sounds, say in games,
the loading procedure could slow you down quite a bit. What would be nice would
be to have a sound file ‘saved’ in some format that could be played
quickly. We can do that!
• What we will do is open the
sound file (say in the Form_Load procedure) and write the file to a string variable.
Then, we just use this string variable in place of the file name in the sndPlaySound
argument list. We also need to ‘Or’ the SndType argument with the
constant SND_MEMORY (this tells sndPlaySound we are playing a sound from memory
as opposed to a WAV file). This technique is borrowed from “Black Art of
Visual Basic Game Programming,” by Mark Pruett, published by The Waite Group
in 1995. Sounds played using this technique must be short sounds (less than 5
seconds) or mysterious results could happen.
Quick Example
8 - Playing Sounds Quickly
We’ll write some code to play a quick ‘bonk’
sound.
-
Start a new application. Add a command button.
-
Copy and paste the sndPlaySound Declare statement and the two needed constants
(see QuickExample 4). Declare a variable
(BongSound) for the sound file. Add SND_MEMORY to the constants declarations.
The two added statements are:
Dim BongSound As String
Private Const SND_MEMORY = &H4
-
Add the following general function, StoreSound, that will copy a WAV file into
a string variable:
Private Function StoreSound(ByVal FileName)
As String
'-----------------------------------------------------
' Load a sound file into a string variable.
' Taken from:
' Mark Pruett
' Black Art of Visual Basic Game Programming
' The Waite Group, 1995
'-----------------------------------------------------
Dim Buffer As String
Dim F As Integer
Dim SoundBuffer As String
On Error GoTo NoiseGet_Error
Buffer = Space$(1024)
SoundBuffer = ""
F = FreeFile
Open FileName For Binary As F
Do While Not EOF(F)
Get #F, , Buffer
SoundBuffer = SoundBuffer & Buffer
Loop
Close F
StoreSound = Trim(SoundBuffer)
Exit Function
NoiseGet_Error:
SoundBuffer = ""
Exit Function
End Function
-
Write the following Form_Load procedure:
Private Sub Form_Load()
BongSound = StoreSound("bong.wav")
End Sub
-
Use this as the Command1_Click procedure:
Private Sub Command1_Click()
Call sndPlaySound(BongSound, SND_SYNC Or SND_MEMORY)
End Sub
-
Make sure the sound (BONK.WAV) is in the same directory as your application.
Run the application. Each time you click the command button, you should hear a
bonk!