Reputation: 403
I'm using NAudio to capture 15 seconds of audio. Like this:
MemoryStream bufferedVoice = new MemoryStream();
voiceCapturer = new WasapiLoopbackCapture(OutputDevice);
voiceCapturer.DataAvailable += onVoiceOutputReceived;
voiceCapturer.StartRecording();
private void onVoiceOutputReceived(object sender, WaveInEventArgs e)
{
bufferedVoice.Write(e.Buffer, 0, e.BytesRecorded);
}
And after 15 seconds I want to save it to a file, and exit. I tried it like this but it didn't work:
var ResourceWaveStream = new RawSourceWaveStream(bufferedVoice, voiceCapturer.WaveFormat);
var SampleProvider = new WaveToSampleProvider(ResourceWaveStream).ToWaveProvider16();
var fileWriter = new WaveFileWriter("output.mp3", SampleProvider.WaveFormat);
byte[] buf = new byte[8192];
while(SampleProvider.Read(buf, 0, buf.Length) > 0)
{
fileWriter.Write(buf, 0, buf.Length);
}
fileWriter.Dispose();
How can I save the memorystream into a file?
Clarification: I only want to store x seconds of audio in memory. So when the max size is reached, some of the oldest part is removed. Then if I press a button, I want to save the 15 seconds of audio into a file.
Now, my question is how should I store the audio in memory, and then write it to a file?
Upvotes: 1
Views: 2275
Reputation: 134
Try this:
using(var fileWriter = new WaveFileWriter("yourOutputFile", SampleProvider.WaveFormat)
{
ResourceWaveStream.CopyTo(fileWriter);
}
Btw, the "using" block is good for you here because it will automatically dispose the writer, allowing the WaveFileWriter to write headers to the file.
Upvotes: 1
Reputation: 403
Okay, I finally have the solution. First, I copy the sound data directly to the memory stream. And then when I need it, I read the whole memorystream into a RawSourceWaveStream
and then I pass that to the final WaveFileWriter
. If anybody is interested in how I did it exactly, then message me.
Thanks.
Upvotes: 0