System.InvalidOperationException: 'RegisterSessionNotification has to be called from an MTA-Thread.'

System.InvalidOperationException: 'RegisterSessionNotification has to be called from an MTA-Thread.'

所以,我正在尝试为峰值音量创建一个可视化工具,我在使用 CsCore 的网站上找到了这段代码。所以当我尝试 运行 时,它抛出了以下错误消息:

System.InvalidOperationException: 'RegisterSessionNotification has to be called from an MTA-Thread.'

这是我正在使用的代码

public static void getVolume() {
        using(var sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render))
        {
            using(var sessionEnumerator = sessionManager.GetSessionEnumerator())
            {
                foreach(var session in sessionEnumerator)
                {
                    using(var audioMeterInformation = session.QueryInterface<AudioMeterInformation>())
                    {
                        Debug.WriteLine(audioMeterInformation.GetPeakValue());
                    }
                }
            }
        }
    }

    private static AudioSessionManager2 GetDefaultAudioSessionManager2(DataFlow dataFlow)
    {
        using(var enumerator = new MMDeviceEnumerator())
        {
            using (var device = enumerator.GetDefaultAudioEndpoint(dataFlow, Role.Multimedia))
            {
                Debug.WriteLine("DefaultDevice: " + device.FriendlyName);
                var sessionManager = AudioSessionManager2.FromMMDevice(device);
                return sessionManager;

            }
        }
    }

谢谢。

在msdn上可以看到下面的备注:

Note Make sure that the application initializes COM with Multithreaded Apartment (MTA) model by calling CoInitializeEx(NULL, COINIT_MULTITHREADED) in a non-UI thread. If MTA is not initialized, the application does not receive session notifications from the session manager. Threads that run the user interface of an application should be initialized apartment threading model.

测试表明您必须从 mta 线程调用此函数。 只需通过一个新线程、一个线程池、一个任务等来执行该方法。 除了主要 ui 线程之外的任何内容。 这些是 windows 核心音频 api 的一些限制。

使用:

Task.Run(() => yourRutine());