I'm a chemistry student trying to use NAudio in C# to gather data from my computer's microphone (planning on switching to an audio port later, in case that's pertinent to how this gets answered). I understand what source streams are, and how NAudio uses an event handler to know whether or not to start reading information from said stream, but I get stumped when it comes to working with the data that has been read from the stream. As I understand it, a buffer array is populated in either byte or WAV format from the source stream (with the AddSamples command). For now, all that I'm trying to do is populate the buffer and write its contents on the console or make a simple visualization. I can't seem to get my values out of the buffer, and I've tried treating it as both a WAV and byte array. Can someone give me a hand in understanding how NAudio works from the ground up, and how to extract the data from the buffer and store it in a more useful format (i.e. doubles)? Here's the code I have so far for handling NAudio and all that comes with it:
public NAudio.Wave.BufferedWaveProvider waveBuffer = null; // clears buffer
NAudio.Wave.WaveIn sourceStream = null; // clears source stream
public void startRecording(int samplingFrequency, int deviceNumber, string fileName)
{
sourceStream = new NAudio.Wave.WaveIn(); // initializes incoming audio stream
sourceStream.DeviceNumber = deviceNumber; // specifies microphone device number
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(samplingFrequency, NAudio.Wave.WaveIn.GetCapabilities(deviceNumber).Channels); // specifies sampling frequency, channels
waveBuffer = new NAudio.Wave.BufferedWaveProvider(sourceStream.WaveFormat); // initializes buffer
sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(sourceStream_DataAvailable); // event handler for when incoming audio is available
sourceStream.StartRecording();
PauseForMilliSeconds(500); // delay before recording is stopped
sourceStream.StopRecording(); // terminates recording
sourceStream.Dispose();
sourceStream = null;
}
void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
waveBuffer.AddSamples(e.Buffer, 0, e.BytesRecorded); // populate buffer with audio stream
waveBuffer.DiscardOnBufferOverflow = true;
}
WaveIn
source will only triggersourceStream_DataAvailable()
when it actually recorded some sounds. When the microphone records nothing then the event handler won't be called. Also, how are you reading the data from theBufferedWaveProvider
? You said you are trying to print/display the audio data, but you are not showing the code that does that. – Good Night Nerd PrideDebug.WriteLine()
command. The main question that I have is: How do I read data from the buffer/use the buffer in general? I've triedArray.Copy
andBlockCopy
to a separate temporary array, but I haven't managed to get anything coherent out. – Ruvim