0

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.

Neb
  • 1
  • 4

2 Answers2

1

Once you've created an instance of WasapiOut you call Init passing the audio you want to play. It will try to use the sample rate (and WaveFormat) of that audio directly, assuming the soundcard supports it. Usi

Mark Heath
  • 48,273
  • 29
  • 137
  • 194
  • Hey mark ! Thanks but I maybe didn't ask the right question. I want for example set the wasapiOut sample rate to 48000, even if I want to play an audio file at 44100. The outputDevice sample rate must stay the same as I chose, and the sample rate of the audio file must also stay the same as it was. I edited my question to add new information. – Neb May 04 '19 at 11:26
0

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".

Neb
  • 1
  • 4