NAudio Asio Record and Playback

2020-02-15 04:58发布

问题:

I'm trying to write my own VST Host and for that i need to record and play audio from an Asio Driver (in my case for an audio interface). That's why i'm trying to use NAudio's AsioOut.

For testing purposes i'm currently just trying to record the input, copy and play it to the output.

My code looks like this:

var asioout = new AsioOut();
BufferedWaveProvider wavprov = new BufferedWaveProvider(new WaveFormat(44100, 2));
asioout.AudioAvailable += new EventHandler<AsioAudioAvailableEventArgs>(asio_DataAvailable);
asioout.InitRecordAndPlayback(wavprov, 2, 25);
asioout.Play();

...

void asio_DataAvailable(object sender, AsioAudioAvailableEventArgs e)
{
    Array.Copy(e.InputBuffers, e.OutputBuffers, e.InputBuffers.Length);
    e.WrittenToOutputBuffers = true;
}

This way i can't hear any output. I also tried it this way:

void asio_DataAvailable(object sender, AsioAudioAvailableEventArgs e)
{
    byte[] buf = new byte[e.SamplesPerBuffer];
    for (int i = 0; i < e.InputBuffers.Length; i++)
    {
        //Marshal.Copy(e.InputBuffers[i], e.OutputBuffers, 0, e.InputBuffers.Length);
        //also tried to upper one but this way i also couldn't hear anything
        Marshal.Copy(e.InputBuffers[i], buf, 0, e.SamplesPerBuffer);
        Marshal.Copy(buf, 0, e.OutputBuffers[i], e.SamplesPerBuffer);
    }
    e.WrittenToOutputBuffers = true;
}

This way i can hear sound in the volume of my input but it's very distorded.

What am i doing wrong here?

PS: I know how to record and playback.... exists but i couldn't really get a complete answer from this thread, just the idea to try it with Marshall.Copy....

回答1:

Your second attempt is more correct than the first: each input buffer must be copied separately. However the final parameter of the copy method should be the number of bytes, not the number of samples in the buffer. This will typically be 3 or 4 bytes per sample, depending on your ASIO bit depth.