Mario Klisanic
Mario Klisanic

Reputation: 607

NAudio record and save microphone input and speaker output

I want to record conversations over Skype or similar applications (these recordings will be processed after being saved). I was trying to accomplish that with NAudio.

So far I managed to record speaker audio using WasapiLoopbackCapture and save it to a WAV file, also I managed to record and save microphone audio using WaveIn. The main problem is that I cannot mix these 2 files into a single file, as stated in the following link: https://github.com/naudio/NAudio/blob/master/Docs/MixTwoAudioFilesToWav.md

The function where I start my recording looks like this:

        waveSourceSpeakers = new WasapiLoopbackCapture();
        string outputFilePath = @"xxxx\xxx\xxx";

        waveFileSpeakers = new WaveFileWriter(outputFilePath, waveSourceSpeakers.WaveFormat);

        waveSourceSpeakers.DataAvailable += (s, a) =>
        {
            waveFileSpeakers.Write(a.Buffer, 0, a.BytesRecorded);
        };

        waveSourceSpeakers.RecordingStopped += (s, a) =>
        {
            waveFileSpeakers.Dispose();
            waveFileSpeakers = null;
            waveSourceSpeakers.Dispose();
        };

        waveSourceSpeakers.StartRecording();

        waveSourceMic = new WaveIn();
        waveSourceMic.WaveFormat = new WaveFormat(44100, 1);

        waveSourceMic.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
        waveSourceMic.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);

        waveFileMic = new WaveFileWriter(@"xxxx\xxx\xxx", waveSourceMic.WaveFormat);

        waveSourceMic.StartRecording();

The function where I try to mix my 2 wav files looks like this:

      using (var reader1 = new AudioFileReader(@"xxx\xxx\file1.wav"))
      using (var reader2 = new AudioFileReader(@"xxx\xxx\file2.wav"))
      {
                var mixer = new MixingSampleProvider(new[] { reader1, reader2 });
                WaveFileWriter.CreateWaveFile16(@"xxxx\xxx\mixed.wav", mixer);
      }

and I get this exception: System.ArgumentException: 'All mixer inputs must have the same WaveFormat' while trying to create MixingSampleProvider.

I was wondering if I am using the right ways to record both audios? Also, it would be great if there is a way to record both audios in one file, but I'm not sure if that is possible.

Upvotes: 2

Views: 3244

Answers (1)

Fildor
Fildor

Reputation: 16059

All mixer inputs must have the same WaveFormat

hints to that yours don't.

Change the line

waveSourceMic.WaveFormat = new WaveFormat(44100, 1);

to

waveSourceMic.WaveFormat = waveSourceSpeakers.WaveFormat;

So, now you will be using the same Format for both Mic and Speakers and the mixer should be fine.

Upvotes: 5

Related Questions