Recording sound in VB

I need to record a 2 second spoken voice (in wav format) in VB with a click of a button. The code should automatically save the recorded voice into a wave file. How do I do that? I don't want to use the Windows Sound Recorder to do that.
siewwingAsked:
Who is Participating?
 
EugenyConnect With a Mentor Commented:
'place two buttons and timer on form
Option Explicit
Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long
Private Declare Function sndPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" (ByVal lpszSoundName As String, ByVal uFlags As Long) As Long

Dim Time_Past As Boolean

Private Sub Command1_Click()
    On Local Error Resume Next
    Dim i As Long, RS As String, cb As Long, t#
    Time_Past = False
    Timer1.Interval = 2 * 1000 '2 seconds interval
    RS = Space$(128)
    Kill "c:\test.wav"
   
    i = mciSendString("open new type waveaudio alias capture", RS, 128, cb)
    i = mciSendString("record capture", RS, 128, cb)
   'HERE YOU CAN TEST TIME OR ANOTHER EVENT TO STOP CAPTURING
    Timer1.Enabled = True
      Do Until Time_Past:
      DoEvents:
      Loop
     i = mciSendString("stop capture", RS, 128, cb)
    i = mciSendString("save capture c:\test.wav", RS, 128, cb)
    i = mciSendString("close capture", RS, 128, cb)

End Sub


'play recordede file
Private Sub Command2_Click()
     Dim i As Long
    i = sndPlaySound("c:\test.wav", 0)
    If i = 0 Then MsgBox "Error! Probably file not found. Modify the code to record and play a .WAV file on your system."
End Sub

'Timer triggered after 2 seconds
Private Sub Timer1_Timer()
 Time_Past = True
 Timer1.Enabled = False
End Sub
0
 
jbilCommented:
Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long
Private Declare Function sndPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" (ByVal lpszSoundName As String, ByVal uFlags As Long) As Long

Private Sub Command1_Click()
On Local Error Resume Next
Dim i As Long, RS As String, cb As Long, t#
Dim start
RS = Space$(500)
Kill "c:\cdtest.wav" 'Delete old wav file there
start = Timer

Do While Timer < (start + 2)
DoEvents
i = mciSendString("open new type waveaudio alias capture", RS, 128, cb)
i = mciSendString("record capture", RS, 128, cb)
Loop

i = mciSendString("stop capture", RS, 128, cb)
i = mciSendString("save capture c:\cdtest.wav", RS, 128, cb)
i = mciSendString("close capture", RS, 128, cb)

End Sub
0
All Courses

From novice to tech pro — start learning today.