Search code examples
c#audiodevicenaudiosample-rate

Change sample rate of audiocard with WasapiOut Naudio


I want to chose a specific sample rate for my audio card programmatically in c# with Naudio. My output is a WasapiOut in exclusive mode.

I already tried a lot of things, but nothing worked and I've searched everywhere and I only found this : How to Change Speaker Configuration in Windows in C#? But they didn't really find a right solution.

Here's my WasapiOut :

var enumerator = new MMDeviceEnumerator();
MMDevice device = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active).FirstOrDefault(d => d.DeviceFriendlyName == name);
outputDevice = new WasapiOut(device, AudioClientShareMode.Exclusive, false,200);

What I don't understand is that here : https://github.com/naudio/NAudio/blob/master/Docs/WasapiOut.md It says that : "If you choose AudioClientShareMode.Exclusive then you are requesting exclusive access to the sound card. The benefits of this approach are that you can specify the exact sample rate you want" And I didn't find anywhere how to specify the sample rate.

If someone here know the answer it would be great, thanks !

Edit :

I think I found a way by doing this :

var waveFormat5 = WaveFormat.CreateIeeeFloatWaveFormat(Int32.Parse(comboBox1.Text), 2);
            var test2 = new MixingSampleProvider(waveFormat5);
            var audioFile = new AudioFileReader("test.wav");
            var input = audioFile;
            test2.ReadFully = true;
            test2.AddMixerInput(new AutoDisposeFileReader(input,waveFormat5));
            outputDevice.Init(test2);

With "outputDevice" as my WasapiOut. So I set the ouputDevice sample rate to the one that I chose with the Mixing Sample Provider and then I send an audiofile to that Mixer, is that the right way to do it ? Because my audiofile sample rate is at 44100, and I chose to put my outputDevice sample rate to also 44100, but when I make outputDevice.Play(), the sound that I ear is faster than the original.


Solution

  • I solved my problem, I used an AudioPlaybackEngine (https://markheath.net/post/fire-and-forget-audio-playback-with) with a MixingSampleProvider, and a try/catch to handle the message error of "the inputs are not a the same sample rate".