Reputation: 8967
I am recording soundbytes using nAudio and I would like to store these directly into variables inside an object instead of writing them to a file.
At the moment, I am recording the data as follows:
internal void start_recording(int device_number, string recording_file)
{
recording_file_name = recording_file;
mic_source_stream = new WaveIn();
mic_source_stream.DeviceNumber = device_number;
mic_source_stream.WaveFormat = new WaveFormat(44100, WaveIn.GetCapabilities(device_number).Channels);
mic_source_stream.DataAvailable += new EventHandler<WaveInEventArgs>(mic_source_stream_DataAvailable);
wave_writer = new WaveFileWriter(recording_file, mic_source_stream.WaveFormat);
mic_source_stream.StartRecording();
}
internal void mic_source_stream_DataAvailable(object sender, WaveInEventArgs e)
{
if (wave_writer == null) return;
wave_writer.Write(e.Buffer, 0, e.BytesRecorded);
wave_writer.Flush();
}
This creates a *.wav file containing the recording.
Instead, I would like keep the audio data in variables, to keep all related recordings into a single object instead of multiple *.wav files in the file system, but nAudio seems to be geared towards recording directly to a file and playing from a file.
If there an easy way to record audio to a variable and play it back from that variable or should I go the silly but simple route of recording to a *.wav file, reading the file to a byte array, then writing the array back to a file before loading it for playback?
Recordings will be very small, so performance is not an issue, it's just that it's grating to write to disk only to read it right back in memory, twice.
Upvotes: 1
Views: 652
Reputation: 49482
I'd recommend simply writing the recorded audio to a MemoryStream
. Then when you want to play back, use a RawSourceWavestream
passing in the MemoryStream
and the WaveFormat
you are recording in. No need to involve the WAV file format at all.
Upvotes: 2
Reputation: 101453
WaveFileWriter has constructor which accepts arbitrary Stream - just pass MemoryStream there. Name of this writer is a bit confusing of course.
Upvotes: 1