Moti
Moti

Reputation: 927

WasapiCapture NAudio

We are using the NAudio Stack written in c# and trying to capture the audio in Exclusive mode with PCM 8kHZ and 16bits per sample.

In the following function:

private void InitializeCaptureDevice()
{
    if (initialized)
        return;

    long requestedDuration = REFTIMES_PER_MILLISEC * 100;

    if (!audioClient.IsFormatSupported(AudioClientShareMode.Shared, WaveFormat) && 
        (!audioClient.IsFormatSupported(AudioClientShareMode.Exclusive, WaveFormat)))
    {
        throw new ArgumentException("Unsupported Wave Format");
    }

    var streamFlags = GetAudioClientStreamFlags();

    audioClient.Initialize(AudioClientShareMode.Shared,
        streamFlags,
        requestedDuration,
        requestedDuration,
        this.waveFormat,
        Guid.Empty);

    int bufferFrameCount = audioClient.BufferSize;
    this.bytesPerFrame = this.waveFormat.Channels * this.waveFormat.BitsPerSample / 8;
    this.recordBuffer = new byte[bufferFrameCount * bytesPerFrame];
    Debug.WriteLine(string.Format("record buffer size = {0}", this.recordBuffer.Length));

    initialized = true;
}

We configured the WaveFormat before calls this function to (8000,1) and also a period of 100 ms. We expected the system to allocate 1600 bytes for the buffer and interval of 100 ms as requested.

But we noticed following occured: 1. the system allocated audioClient.BufferSize to be 4800 and "this.recordBuffer" an array of 9600 bytes (which means a buffer for 600ms and not 100ms). 2. the thread is going to sleep and then getting 2400 samples (4800 bytes) and not as expected frames of 1600 bytes

Any idea what is going there?

Upvotes: 1

Views: 4301

Answers (1)

Mark Heath
Mark Heath

Reputation: 49522

You say you are capturing audio in exclusive mode, but in the example code you call the Initialize method with AudioClientMode.Shared. It strikes me as very unlikely that shared mode will let you work at 8kHz. Unlike the wave... APIs, WASAPI does no resampling for you of playback or capture, so the soundcard itself must be operating at the sample rate you specify.

Upvotes: 3

Related Questions