This project has moved. For the latest updates, please go here.

Code Review: WasapiCapture.CaptureThread(AudioClient client)

Jan 25, 2012 at 1:52 PM


I am studing the WasapiCapture class and I got a question about the CaptureThread().



    public class WasapiCapture : IWaveIn
        private AudioClient audioClient;

        // Note the parameter
        public void StartRecording()
            // ...
            ThreadStart start = delegate { this.CaptureThread(audioClient); };
            // ...

        // client == audioClient
        // shouldn't the "audioClient" be replaced with the "client"
        private void CaptureThread(AudioClient client)
            int bufferFrameCount = audioClient.BufferSize;
            // Calculate the actual duration of the allocated buffer.
            long actualDuration = (long)((double)REFTIMES_PER_SEC *
                             bufferFrameCount / WaveFormat.SampleRate);
            int sleepMilliseconds = (int)(actualDuration / REFTIMES_PER_MILLISEC / 2);
            AudioCaptureClient capture = client.AudioCaptureClient;

                Debug.WriteLine(string.Format("sleep: {0} ms", sleepMilliseconds));
                while (!this.stop)

                if (RecordingStopped != null)
                    RecordingStopped(this, EventArgs.Empty);
                // don't dispose - the AudioClient only gets disposed when WasapiCapture is disposed

            System.Diagnostics.Debug.WriteLine("stop wasapi");

As I understand the CaptureThread takes AudioClient as a parameter for encapsulation mean but once is used the class field "audioClient.BufferSize" instead of the local "client.BufferSize". Is there any specific reason for doing this or might it be it there unnoticed? Probably this will not cause any issue right now. I decided to mention it for the sake of code readability (i.e. understanding).

In any case I suggest to consider small change in the coding style. The class field names could use underscore prefix like "_audioClient". In this case you do not have to worry to mix local variables with fields or use "this" keyword. The "this" keyword in this project is redundant and in most cases it is safe to remove it (in 512 cases to be exact).

Just trying to be helpful for the sake of the good project.


Jan 25, 2012 at 4:06 PM

About audioClient and client, yes, the thread function could just use its parameter, but they are always the same object so it is not a real issue.

As for underscores, that is a coding preference, and makes no difference to the compiled IL, and I have no plans to change the NAudio codebase in this way at the moment.

thanks for your feedback