Search code examples
c#naudio

How to record audio using naudio onto byte[] rather than file


I am able to capture audio using naudio into file, now i want it on byte[] or Stream in c#.

this.writer = new WaveFileWriter(this.outputFilename, this.waveIn.WaveFormat);

What i tried so far is instead of passing output filename in WaveFileWriter constructor, passed MemoryStream object. With reference to stream object i try to play it using Soundplayer once recording gets over.

private IWaveIn waveIn;
private WaveFileWriter writer;
private string outputFilename;

private Stream memoryStream;

public void onRecord(object inputDevice, string fileName)
{
    if (this.waveIn == null)
    {
            this.outputFilename = fileName;
            this.waveIn = new WasapiLoopbackCapture((MMDevice)inputDevice);

            if(memoryStream == null)
                   memoryStream = new MemoryStream();

            this.writer = new WaveFileWriter(this.memoryStream,this.waveIn.WaveFormat);
            this.waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(this.OnDataAvailable);
            this.waveIn.RecordingStopped += new EventHandler<StoppedEventArgs>(this.OnRecordingStopped);
            this.waveIn.StartRecording();
    }
}

private void OnDataAvailable(object sender, WaveInEventArgs e)
{
    this.writer.Write(e.Buffer, 0, e.BytesRecorded);
}

public void OnRecordingStopped(object sender, StoppedEventArgs e)
{
    if (this.waveIn != null)
    {
            this.waveIn.Dispose();
        this.waveIn = null;
    }

    if (this.writer != null)
    {
        this.writer.Close();
        this.writer = null;
    } 
}

For testing purpose, i created this below code to check whether it able to play the recorded audio.

System.Media.SoundPlayer soundPlayer = new System.Media.SoundPlayer();

memoryStream.Position = 0; 
soundPlayer.Stream = null;
soundPlayer.Stream = memoryStream;
soundPlayer.Play();

But when i try with above manner, i got System.ObjectDisposedException: Cannot access a closed Stream. On the line memoryStream.Position = 0; .I didn't dispose the stream object, Don't know where exactly it gets disposed.


Solution

  • As Mark suggests, i wrapped the memoryStream with IgnoreDisposeStream and it works.

    this.writer = new WaveFileWriter(new IgnoreDisposeStream(memoryStream),this.waveIn.WaveFormat);