Search code examples
c#wpfaudiocscore

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


So, I am trying to create a visualizer for the peak volume and I found this piece of code in the website which uses CsCore. So when I tried running it, it threw the following error message:

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

This is the piece of code I am working with

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;

            }
        }
    }

Thanks.


Solution

  • On msdn, you can see the following remark:

    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.

    Tests showed that you have to call this function from an mta thread. Just execute the method through a new thread, a threadpool, a task, etc. Just anything than the main ui thread. These are some limitations of the windows core audio api's.