naudio / NAudio

Audio and MIDI library for .NET
MIT License
5.55k stars 1.1k forks source link

Wrong ASIO input signal frequency #1070

Open devklee opened 1 year ago

devklee commented 1 year ago

I have a signal generator, it delivers a saw signal ~4731 Hz. It is measured with oscilloscope. Signal goes to ASIO audio interface (48000 samplaes rate). Signal is recorded with Riper, Riper shows ~4742 Hz, that's OK.

I do the same with small test program:

  private static readonly int CONFIG_SAMPLE_RATE = 48000;

  public static void DemoAsioSingleChannel5(AsioOut asioOut, int sampleRate)
  {
      float[] samplesArray = new float[sampleRate * 2];
      WaveFormat waveFormat = new WaveFormat(sampleRate, 24, 2);
      using WaveFileWriter writer = new WaveFileWriter(@"c:\temp\output.wav", waveFormat);

      asioOut.InitRecordAndPlayback(null, 1, sampleRate);
      asioOut.AudioAvailable += OnAsioOutAudioAvailable;
      asioOut.Play(); // start recording

      Console.WriteLine("(press any key to exit)");
      Console.ReadKey();
      asioOut.Stop();
      asioOut.Dispose();

      writer.Close();

      void OnAsioOutAudioAvailable(object? sender, AsioAudioAvailableEventArgs e)
      {
          e.GetAsInterleavedSamples(samplesArray);
          writer.WriteSamples(samplesArray, 0, e.SamplesPerBuffer);
      }
  }

Then I open this file in Riper and measure frequency: 9607 Hz!

image

+/-% doesn't matter, but difference in this case is too big :-)

Can anyone tell me what I'm doing wrong here? Thank you!

pallabs-emerychen commented 11 months ago

Your waveFormat has two channels but the asioOut has only one channel input. The audio player will interpret the file twice higher than the exact frequency, as it splits the data into two sets for playback.