5

I'm trying to get a list of processes that have audio. The processes that display in Volume Mixer.

Currently I have:

var currentProcess = Process.GetProcesses();
foreach (Process Proc in currentProcess.Where(p => p.MainWindowHandle != IntPtr.Zero))
{
     Console.WriteLine(Proc.ProcessName);
}

Which list applications that have a window, is there a way to filter this further to only display audio processes?

Thank you!

KrystianB
  • 502
  • 4
  • 14
  • 2
    This is going to likely require calls into the Windows Core Audio APIs that exist in Windows Vista and newer. Unfortunately, this is a C++ API and doesn't expose a .NET interface. – Powerlord Aug 26 '18 at 21:24
  • 1
    check this out - https://stackoverflow.com/questions/938955/detect-processes-using-audio-on-windows – Ctznkane525 Aug 26 '18 at 22:02

1 Answers1

5

Thanks to this post
I was able to modify one of the methods to return all of the audio processes

    public static List<Process> GetAudioProcesses()
    {
        IMMDeviceEnumerator deviceEnumerator = null;
        IAudioSessionEnumerator sessionEnumerator = null;
        IAudioSessionManager2 mgr = null;
        IMMDevice speakers = null;
        List<Process> audioProcesses = new List<Process>();
        try
        {
            // get the speakers (1st render + multimedia) device
            deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);

            // activate the session manager. we need the enumerator
            Guid IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID;
            object o;
            speakers.Activate(ref IID_IAudioSessionManager2, 0, IntPtr.Zero, out o);
            mgr = (IAudioSessionManager2)o;

            // enumerate sessions for on this device
            mgr.GetSessionEnumerator(out sessionEnumerator);
            int count;
            sessionEnumerator.GetCount(out count);

            // search for an audio session with the required process-id
            for (int i = 0; i < count; ++i)
            {
                IAudioSessionControl2 ctl = null;
                try
                {
                    sessionEnumerator.GetSession(i, out ctl);
                    ctl.GetProcessId(out int cpid);

                    audioProcesses.Add(Process.GetProcessById(cpid));
                }
                finally
                {
                    if (ctl != null) Marshal.ReleaseComObject(ctl);
                }
            }

            return audioProcesses;
        }
        finally
        {
            if (sessionEnumerator != null) Marshal.ReleaseComObject(sessionEnumerator);
            if (mgr != null) Marshal.ReleaseComObject(mgr);
            if (speakers != null) Marshal.ReleaseComObject(speakers);
            if (deviceEnumerator != null) Marshal.ReleaseComObject(deviceEnumerator);
        }
    }
KrystianB
  • 502
  • 4
  • 14