I'm attempting to route microphone audio into the speakers in NAudio, using ASIO drivers. I have been successful in the NAudio demo project. Copying this code over to a different project (XNA, if relevant) is causing a COMException every time. Here is the method I wrote:
[STAThread]
void InitAsio()
{
if (this.asioOut != null &&
(this.asioOut.DriverName != "ASIO4ALL v2" ||
this.asioOut.ChannelOffset != 0))
{
this.asioOut.AudioAvailable -= asioOut_AudioAvailable;
this.asioOut.Dispose();
this.asioOut = null;
}
// create wave input from mic
// create device if necessary
if (this.asioOut == null)
{
this.asioOut = new AsioOut();
BufferedWaveProvider wavprov = new BufferedWaveProvider(new WaveFormat(44100, 1));
this.asioOut.InputChannelOffset = 0;
this.asioOut.InitRecordAndPlayback(wavprov, 1, 44100);
this.asioOut.AudioAvailable += asioOut_AudioAvailable;
}
//this.fileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".wav");
//this.writer = new WaveFileWriter(fileName, new WaveFormat(44100, recordChannelCount));
this.asioOut.Play();
}
Every time, this method fails in AsioDriver.cs:
int hresult = CoCreateInstance(ref ASIOGuid, IntPtr.Zero, CLSCTX_INPROC_SERVER, ref ASIOGuid, out pASIOComObject);
if ( hresult != 0 )
{
throw new COMException("Unable to instantiate ASIO. Check if STAThread is set",hresult);
}
I have no idea what's happening and why. Same code works in the NAudio demo project. Any ideas?
The STAThread
attribute can only be applied to the Main
method of your application. It won't work on any other method.