音频:"Unable to instantiate ASIO. Check if STAThread is set"

NAudio: "Unable to instantiate ASIO. Check if STAThread is set"

我正在尝试使用 ASIO 驱动程序将麦克风音频路由到 NAudio 中的扬声器。我在 NAudio 演示项目中取得了成功。每次将此代码复制到不同的项目(XNA,如果相关)都会导致 COMException。这是我写的方法:

    [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();
    }

每次,此方法都会在 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);
    }

我不知道发生了什么,也不知道为什么。相同的代码适用于 NAudio 演示项目。有什么想法吗?

STAThread 属性只能应用于应用程序的 Main 方法。它不适用于任何其他方法。