Search code examples
c#wpfnaudiowasapi

Record audio using NAudio Wasapi wrapper, sound file weight is not 0 but audio is blank


What is working - Save file

What is not: - Audio file is blank (as a length but no audible sound, aka sound is blank) Edit (for clarity): The file weight is not 0.

Already implemented a solution with winmm.dll but looking for something better than 16-bit quality. Already using NAudio wrapper for libmp3lame dll so using NAudio is a viable option.

public void Start()
        {
            if(this.isInitialized)
            {
                string outputFilePath = "...";
                this.capture = new NAudio.Wave.WasapiLoopbackCapture();
                this.writer = new NAudio.Wave.WaveFileWriter(outputFilePath, this.capture.WaveFormat);

                this.capture.DataAvailable += (s, a) =>
                {
                    this.writer.Write(a.Buffer, 0, a.BytesRecorded);
                };

                this.capture.RecordingStopped += (s, a) =>
                {
                    this.writer.Dispose();
                    this.writer = null;
                    this.capture.Dispose();
                };

                this.capture.StartRecording();
            }


        }

        public void StopAndSave()
        {
            if(this.isInitialized)
            {
                this.capture.StopRecording();
            }
        }

Expected: to record audio in a WAV audio file format

this.isInitialized check for path and file naming convention. Because the file save to expected location did not added the code. This code part is working as expected.

Note - using NAudio 1.8.5 - target system is Win10 x64 pro


Solution

  • You are using WasapiLoopbackCapture which attempts to capture audio being played on the computer. If you meant to capture an input device (like a microphone), you should use WasapiCapture instead.