Search code examples
c#cscore

Get processname or ID from CSCore audiostream


I have filtered all audio streams from my programs with CSCore lib. It works fine, but I have no idear which stream belong to which process. Is there a way to get the processId oder processname per stream?

my code:

public class Audio
{
    public static void start(ListBox device, ListBox process)
    {
        using (var sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render))
        {

            using (var sessionEnumerator = sessionManager.GetSessionEnumerator())
            {

                foreach (var session in sessionEnumerator)
                {
                    using (var audioMeterInformation = session.QueryInterface<AudioMeterInformation>())
                    {
                        device.Items.Add(audioMeterInformation.GetPeakValue());

                        process.Items.Add("here I need the processname or ID");
                    }
                }
            }
        }


    }

    private static AudioSessionManager2 GetDefaultAudioSessionManager2(DataFlow dataFlow)
    {
        using (var enumerator = new MMDeviceEnumerator())
        {
            using (var device = enumerator.GetDefaultAudioEndpoint(dataFlow, Role.Multimedia))
            {
                var sessionManager = AudioSessionManager2.FromMMDevice(device);
                return sessionManager;
            }
        }
    }
}

thanks a lot!


Solution

  • You have to query an instance of the AudioSessionControl2 object:

    public class Audio
    {
        public static void start(ListBox device, ListBox process)
        {
            using (var sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render))
            {
    
                using (var sessionEnumerator = sessionManager.GetSessionEnumerator())
                {
                    foreach (var session in sessionEnumerator)
                    {
                        using (var audioMeterInformation = session.QueryInterface<AudioMeterInformation>())
                        using(var session2 = session.QueryInterface<AudioSessionControl2>())
                        {
                            device.Items.Add(audioMeterInformation.GetPeakValue());
                            var processID = session2.ProcessID;
                            process.Items.Add("here I need the processname or ID");
                        }
                    }
                }
            }
    
    
        }
    
        private static AudioSessionManager2 GetDefaultAudioSessionManager2(DataFlow dataFlow)
        {
            using (var enumerator = new MMDeviceEnumerator())
            {
                using (var device = enumerator.GetDefaultAudioEndpoint(dataFlow, Role.Multimedia))
                {
                    var sessionManager = AudioSessionManager2.FromMMDevice(device);
                    return sessionManager;
                }
            }
        }
    }