Reputation: 77
I'm working on a voice recording program using Naudio Library. Right now to record I have to press on record button and than the save button. I want to make the program recording all the time and save the recorded audio automatically. Thanks for helping. here's some of the code. start recording:
NAudio.Wave.WaveIn sourceStream = null;
NAudio.Wave.WaveFileWriter waveWriter = null;
private void SRecording_Click(object sender, EventArgs e)
{
if (sourceList.SelectedItems.Count == 0) return;
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Wave File (*.wav)|*.wav;";
string wavoutputpath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
wavoutputpath += "\\Speech.wav";
save.FileName = wavoutputpath;
int deviceNumber = sourceList.SelectedItems[0].Index;
sourceStream = new NAudio.Wave.WaveIn();
sourceStream.DeviceNumber = deviceNumber;
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(44100, NAudio.Wave.WaveIn.GetCapabilities(deviceNumber).Channels);
sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(sourceStream_DataAvailable);
waveWriter = new NAudio.Wave.WaveFileWriter(save.FileName, sourceStream.WaveFormat);
sourceStream.StartRecording();
}
private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
if (waveWriter == null) return;
waveWriter.WriteData(e.Buffer, 0, e.BytesRecorded);
waveWriter.Flush();
}
stop recording:
if (sourceStream != null)
{
sourceStream.StopRecording();
sourceStream.Dispose();
sourceStream = null;
}
if (waveWriter != null)
{
waveWriter.Dispose();
waveWriter = null;
}
Upvotes: 2
Views: 1999
Reputation: 2710
@Jester has a good answer, just no code to help others out that have no idea on how to implement this.
Audio is not my area of expertise, however, here is what I came up with:
int threshold = <SETYOURTHRESHOLD>;
int value = Math.Abs(BitConverter.ToInt16(e.Buffer, (e.BytesRecorded - 2)));
if (value < threshold)
sourceStream.StopRecording();
all in the:
public void sourceStream_DataAvailable(object sender, WaveInEventArgs e)
Method.
Of course this is only a start and more work is required to turn this into a fine running machine!
Upvotes: 0
Reputation: 3489
If all you want to do it stop the recording when there is no audio, you can check if a certain number of 'silent' samples has passed. In the WaveIn.DataAvailable
event handler, you can examine each sample by looking at the bytes in e.Buffer
. Say you are recording in 16 bit
, every 2 bytes
forms one sample. You can convert it to an Int16
to examine it. Also for starting recording when audio is available again, you can examine the sample value and if it exceeds a threshold value, you can start writing it.
Upvotes: 3