How to record and play back with NAudio using AsioOut

I am trying to get audio input and send the output directly with less delay possible with C #.

I use the NAudio library , which supports ASIO for better latency.

In particular, I use an AsioOut object for recording, and another for playback, initialized with a BufferedWaveProvider , which is populated with a callback function: OnAudioAvailable , which allows me to use ASIO buffers.

The problem is that I hear sound with various glitches and with a bit of delay . I think the problem is the OnAudioAvailable function, where the buffer is filled with data taken as input from the sound card.

Ads:

NAudio.Wave.AsioOut playAsio;
NAudio.Wave.AsioOut recAsio;
NAudio.Wave.BufferedWaveProvider buffer;

Playback Order:

if (sourceList.SelectedItems.Count == 0) return;

int deviceNumber = sourceList.SelectedItems[0].Index;

recAsio = new NAudio.Wave.AsioOut(deviceNumber);
recAsio.InitRecordAndPlayback(null, 2, 44100); //rec channel = 1

NAudio.Wave.WaveFormat formato = new NAudio.Wave.WaveFormat();
buffer = new NAudio.Wave.BufferedWaveProvider(formato);

recAsio.AudioAvailable += new EventHandler<NAudio.Wave.AsioAudioAvailableEventArgs>(OnAudioAvailable);

//Collego l'output col buffer
playAsio = new NAudio.Wave.AsioOut(deviceNumber);
playAsio.Init(buffer);

//Registro
recAsio.Play();
//Playback
playAsio.Play();

OnAudioAvailable ():

//Callback
private unsafe void OnAudioAvailable(object sender, NAudio.Wave.AsioAudioAvailableEventArgs e)
{
    //Copio tutti gli elementi di InputBuffers in buf e li aggiungo in coda al buffer
    byte[] buf = new byte[e.SamplesPerBuffer];
    for (int i = 0; i < e.InputBuffers.Length; i++)
    {
        Marshal.Copy(e.InputBuffers[i], buf, 0, e.SamplesPerBuffer);
        //Aggiungo in coda al buffer
        buffer.AddSamples(buf, 0, buf.Length);
    }
}

AsioAudioAvailableEventArgs definition:

public AsioAudioAvailableEventArgs(IntPtr[] inputBuffers, int samplesPerBuffer, AsioSampleType asioSampleType);
public float[] GetAsInterleavedSamples();

Does anyone know how to fix this? Thanks to everyone.

0
source share
1 answer

You cannot use two instances AsioOutfor the same device. I am surprised that this works at all. Just use one, s InitRecordAndPlayback.

AudioAvailableEvent OutputBuffers WrittenToOutputBuffers = true. , BufferedWaveProvider.

, - , AudioAvailable . ASIO, (, 10 ) (, 96 , 8 ). . .NET , .

+2

Source: https://habr.com/ru/post/1532727/


All Articles