The recording will be via the computer microphone and we will need buttons to stop and start the recording
Add a button to your windows form and set the following properties
- Name = BtnRecord
- Text = Record
- Enabled = True
- Name = BtnStop
- Text = Stop
- Enabled = False
Add these lines immediately after the Public Class .... statement
Private wavesource As NAudio.Wave.WaveIn = Nothing
Private wavefile As NAudio.Wave.WaveFileWriter = Nothing
and insert the following before the End Class statement
Private Sub BtnRecord_Click(sender As Object, e As EventArgs) Handles BtnRecord.Click
BtnRecord.Enabled = False
BtnStop.Enabled = True
wavesource = New NAudio.Wave.WaveIn With {
.WaveFormat = New NAudio.Wave.WaveFormat(44100, 1)
}
AddHandler wavesource.DataAvailable, AddressOf WaveSource_DataAvailable
AddHandler wavesource.RecordingStopped, AddressOf WaveSource_RecordingStopped
wavefile = New NAudio.Wave.WaveFileWriter("C:\digitaldan\Test0001.wav", wavesource.WaveFormat)
wavesource.StartRecording()
End Sub
Private Sub BtnStop_Click(sender As Object, e As EventArgs) Handles BtnStop.Click
BtnStop.Enabled = False
wavesource.StopRecording()
End Sub
Public Sub WaveSource_DataAvailable(sender As Object, e As NAudio.Wave.WaveInEventArgs)
If wavefile IsNot Nothing Then
wavefile.Write(e.Buffer, 0, e.BytesRecorded)
wavefile.Flush()
End If
End Sub
Private Sub WaveSource_RecordingStopped(sender As Object, e As NAudio.Wave.StoppedEventArgs)
If (wavesource Is Nothing) Then
wavesource.Dispose()
wavesource = Nothing
End If
If wavefile Is Nothing Then
wavefile.Dispose()
wavefile = Nothing
End If
BtnRecord.Enabled = True
End Sub
NAudio Licence
Copyright 2020 Mark HeathPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Note Recording sound in WAV format can use a lot of disk space (especially if accidentaly left recording unattended.) You may wish to modify the code to limit the size of any recordings. (e.g. use a Timer event to automatically stop all recording 1 hour after a recording starts.)
DigitalDan.co.uk