1

I have a little problem with the following C# code using ASIO and the NAudio library.

I try to get sound from a guitar and directly play the sound of it in the speakers. So far it works, but the sound is very distorted. I've read here that a way to slove that is by doing:

Marshal.Copy(buf, 0, e.OutputBuffers[i], e.SamplesPerBuffer * 4);

But, if I do that, the size of the buffer is 4 times bigger, so the code won't compile.

I've tried that with asio4all and a MAUDIO card; it's the same problem on both of them.

public partial class MainWindow : Window
{
    AsioOut ASIODriver;
    BufferedWaveProvider buffer;
    public MainWindow()
    {
        String[] drivernames = AsioOut.GetDriverNames();
        ASIODriver = new AsioOut(drivernames[0]);

        buffer = new BufferedWaveProvider(new WaveFormat ());
        ASIODriver.AudioAvailable += new EventHandler<AsioAudioAvailableEventArgs>(ASIODriver_AudioAvailable);
        ASIODriver.InitRecordAndPlayback(buffer,2,44100);
        //ASIODriver.InputChannelOffset = 1;
        ASIODriver.Play();       
    }

    private void ASIODriver_AudioAvailable(object sender, AsioAudioAvailableEventArgs e)
    {
        byte[] buf = new byte[e.SamplesPerBuffer];
        for (int i = 0; i < e.InputBuffers.Length; i++)
        {
           Marshal.Copy(e.InputBuffers[i], buf, 0, e.SamplesPerBuffer);
           Marshal.Copy(buf, 0, e.OutputBuffers[i], e.SamplesPerBuffer); 
        }
        e.WrittenToOutputBuffers = true;
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

Solution by OP.

The solution was to increase the size of the buffer. See the commented lines and their following one for the changes.

public partial class MainWindow : Window
{
    AsioOut ASIODriver;
    BufferedWaveProvider buffer;
    public MainWindow()
    {
        String[] drivernames = AsioOut.GetDriverNames();
        ASIODriver = new AsioOut(drivernames[0]);

        buffer = new BufferedWaveProvider(new WaveFormat ());
        ASIODriver.AudioAvailable += new EventHandler<AsioAudioAvailableEventArgs>(ASIODriver_AudioAvailable);
        ASIODriver.InitRecordAndPlayback(buffer,2,44100);
        ASIODriver.Play();       
    }

    private void ASIODriver_AudioAvailable(object sender, AsioAudioAvailableEventArgs e)
    {
        //byte[] buf = new byte[e.SamplesPerBuffer];
        byte[] buf = new byte[e.SamplesPerBuffer*4];
        for (int i = 0; i < e.InputBuffers.Length; i++)
        {
           //Marshal.Copy(e.InputBuffers[i], buf, 0, e.SamplesPerBuffer);
           //Marshal.Copy(buf, 0, e.OutputBuffers[i], e.SamplesPerBuffer);
           Marshal.Copy(e.InputBuffers[i], buf, 0, e.SamplesPerBuffer*4);
           Marshal.Copy(buf, 0, e.OutputBuffers[i], e.SamplesPerBuffer*4);
        }
        e.WrittenToOutputBuffers = true;
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267