GetCount() private method

private GetCount ( int* SessionCount ) : HRESULT,
SessionCount int*
return HRESULT,
コード例 #1
0
        private static T GetCoreAudioObject <T>(int pid)
        {
            IMMDevice             speakers = VolumeMixer.GetOutputDevice();
            IAudioSessionManager2 mgr      = VolumeMixer.GetOutputDeviceSessionManager(speakers);

            IAudioSessionEnumerator sessionEnumerator = VolumeMixer.GetOutputDeviceSessionEnumerator(mgr);
            int count;

            sessionEnumerator.GetCount(out count);

            dynamic volumeControl = null;

            for (int i = 0; i < count; i++)
            {
                IAudioSessionControl2 ctl;
                sessionEnumerator.GetSession(i, out ctl);
                int cpid;
                ctl.GetProcessId(out cpid);

                if (cpid == pid)
                {
                    volumeControl = (T)ctl;
                    break;
                }

                Marshal.ReleaseComObject(ctl);
            }

            Marshal.ReleaseComObject(sessionEnumerator);
            Marshal.ReleaseComObject(mgr);
            Marshal.ReleaseComObject(speakers);
            return(volumeControl);
        }
コード例 #2
0
ファイル: Volume.cs プロジェクト: navam1915/Gw2Launcher
            /// <summary>
            /// Iterates through process IDs that have a volume controller
            /// </summary>
            public IEnumerable <int> EnumerateProcesses()
            {
                if (!isSupported)
                {
                    yield break;
                }

                IAudioSessionEnumerator sessionEnumerator = null;

                try
                {
                    mgr.GetSessionEnumerator(out sessionEnumerator);
                    int count;
                    sessionEnumerator.GetCount(out count);

                    for (int i = 0; i < count; i++)
                    {
                        IAudioSessionControl2 ctl;
                        sessionEnumerator.GetSession(i, out ctl);
                        int cpid;
                        ctl.GetProcessId(out cpid);

                        Marshal.ReleaseComObject(ctl);

                        yield return(cpid);
                    }
                }
                finally
                {
                    if (sessionEnumerator != null)
                    {
                        Marshal.ReleaseComObject(sessionEnumerator);
                    }
                }
            }
コード例 #3
0
        private static ISimpleAudioVolume GetVolumeObject(string name)
        {
            IMMDeviceEnumerator devices = (IMMDeviceEnumerator) new MMDeviceEnumerator();
            IMMDevice           device  = devices.GetDefaultAudioEndpoint(EDATAFLOW_RENDER, EROLE_MULTIMEDIA);

            Guid sessionManagerGUID          = typeof(IAudioSessionManager2).GUID;
            IAudioSessionManager2   manager  = (IAudioSessionManager2)device.Activate(ref sessionManagerGUID, 0, IntPtr.Zero);
            IAudioSessionEnumerator sessions = manager.GetSessionEnumerator();

            ISimpleAudioVolume volumeObj = null;

            for (int index = sessions.GetCount() - 1; index >= 0; index--)
            {
                IAudioSessionControl2 ctl = sessions.GetSession(index) as IAudioSessionControl2;

                if (ctl != null)
                {
                    string identifier = ctl.GetSessionIdentifier();

                    if (identifier != null && identifier.Contains(name))
                    {
                        volumeObj = ctl as ISimpleAudioVolume;
                        break;
                    }

                    Marshal.ReleaseComObject(ctl);
                }
            }

            Marshal.ReleaseComObject(devices);
            Marshal.ReleaseComObject(device);
            Marshal.ReleaseComObject(manager);
            Marshal.ReleaseComObject(sessions);
            return(volumeObj);
        }
コード例 #4
0
        // Lists all devices, and for each device all processes that are currently playing sound using that device
        public static List <SoundInfoDevice> getSoundInfo()
        {
            List <SoundInfoDevice> soundInfoDevices = new List <SoundInfoDevice>();

            DeviceEnumerator    enumerator       = new DeviceEnumerator();
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)enumerator;
            IMMDeviceCollection deviceCollection = deviceEnumerator.EnumAudioEndpoints(EDataFlow.eRender, DeviceStatemask.DEVICE_STATE_ACTIVE);
            uint deviceCount = deviceCollection.GetCount();

            for (uint i = 0; i < deviceCount; i++)
            {
                SoundInfoDevice soundInfoDevice = new SoundInfoDevice();
                soundInfoDevices.Add(soundInfoDevice);

                IMMDevice device   = deviceCollection.Item(i);
                string    deviceId = device.GetId();
                soundInfoDevice.ID = deviceId;
                IMMPropertyStore propertyStore         = device.OpenPropertyStore(ProperyStoreMode.STGM_READ);
                PropertyKey      propertyKeyDeviceDesc = new PropertyKey();
                propertyKeyDeviceDesc.fmtid = new Guid(0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0);
                propertyKeyDeviceDesc.pid   = 2;
                PropVariant deviceNamePtr = propertyStore.GetValue(ref propertyKeyDeviceDesc);
                string      deviceName    = Marshal.PtrToStringUni(deviceNamePtr.pszVal);
                soundInfoDevice.name = deviceName;

                Guid guidAudioSessionManager2             = new Guid("77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F");
                IAudioSessionManager2 audioSessionManager = (IAudioSessionManager2)device.Activate(ref guidAudioSessionManager2, (int)ClsCtx.CLSCTX_ALL, IntPtr.Zero);


                IAudioSessionEnumerator sessionEnumerator = audioSessionManager.GetSessionEnumerator();

                int sessionCount = sessionEnumerator.GetCount();
                for (int j = 0; j < sessionCount; j++)
                {
                    IAudioSessionControl  audioSessionControl  = sessionEnumerator.GetSession(j);
                    IAudioSessionControl2 audioSessionControl2 = (IAudioSessionControl2)audioSessionControl;
                    AudioSessionState     state = audioSessionControl.GetState();
                    if (state == AudioSessionState.AudioSessionStateActive)
                    {
                        SoundInfoSession soundInfoSession = new SoundInfoSession();
                        soundInfoDevice.sessions.Add(soundInfoSession);

                        string displayName = audioSessionControl.GetDisplayName();
                        string iconPath    = audioSessionControl.GetIconPath();
                        int    processId   = audioSessionControl2.GetProcessId();
                        string processName = Process.GetProcessById(processId).MainWindowTitle;

                        soundInfoSession.pid        = processId;
                        soundInfoSession.windowName = processName;
                    }
                }
            }

            return(soundInfoDevices);
        }
コード例 #5
0
ファイル: Volume.cs プロジェクト: navam1915/Gw2Launcher
        private static ISimpleAudioVolume GetVolumeObject(int pid)
        {
            IMMDeviceEnumerator     deviceEnumerator  = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice               speakers          = null;
            IAudioSessionEnumerator sessionEnumerator = null;
            IAudioSessionManager2   mgr = null;

            try
            {
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);

                Guid   IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID;
                object o;
                speakers.Activate(ref IID_IAudioSessionManager2, 0, IntPtr.Zero, out o);
                mgr = (IAudioSessionManager2)o;

                mgr.GetSessionEnumerator(out sessionEnumerator);
                int count;
                sessionEnumerator.GetCount(out count);

                ISimpleAudioVolume volumeControl = null;
                for (int i = 0; i < count; i++)
                {
                    IAudioSessionControl2 ctl;
                    sessionEnumerator.GetSession(i, out ctl);
                    int cpid;
                    ctl.GetProcessId(out cpid);

                    if (cpid == pid)
                    {
                        volumeControl = ctl as ISimpleAudioVolume;
                        break;
                    }
                    Marshal.ReleaseComObject(ctl);
                }

                return(volumeControl);
            }
            finally
            {
                Marshal.ReleaseComObject(sessionEnumerator);
                Marshal.ReleaseComObject(mgr);
                Marshal.ReleaseComObject(speakers);
                Marshal.ReleaseComObject(deviceEnumerator);
            }
        }
コード例 #6
0
        public AudioSessionControl FindSession(IAudioSessionManager2 session_manager, AudioSessionProc matchsession_proc, object data)
        {
            AudioSessionControl     res         = null;
            IAudioSessionEnumerator sessionList = null;

            session_manager.GetSessionEnumerator(out sessionList);
            if (sessionList == null)
            {
                return(null);
            }

            int cnt = 0;

            sessionList.GetCount(out cnt);

            for (int index = 0; index < cnt; index++)
            {
                IAudioSessionControl session = null;
                sessionList.GetSession(index, out session);
                if (session == null)
                {
                    continue;
                }

                bool quit = false;
                AudioSessionControl control = null;
                try
                {
                    control = new AudioSessionControl(session);
                    quit    = (matchsession_proc(control, data) == false);
                    if (quit)
                    {
                        res = control;
                        break;
                    }
                    control.Dispose();
                    Marshal.Release(Marshal.GetIUnknownForObject(session));
                }
                catch { }
                {
                }
            }
            Marshal.Release(Marshal.GetIUnknownForObject(sessionList));
            GC.WaitForPendingFinalizers();
            return(res);
        }
コード例 #7
0
            // Get audio controls and process Ids for audio sessions from enumerator
            public static IDictionary <int, IAudioSessionControl2> GetAudioContols(IAudioSessionEnumerator sessions)
            {
                int count;

                sessions.GetCount(out count);
                IDictionary <int, IAudioSessionControl2> controls = new Dictionary <int, IAudioSessionControl2>();

                for (int i = 0; i < count; i++)
                {
                    IAudioSessionControl2 ctl;
                    sessions.GetSession(i, out ctl);
                    int cpid;
                    ctl.GetProcessId(out cpid);
                    controls[cpid] = ctl;
                }
                return(controls);
            }
コード例 #8
0
ファイル: Volume.cs プロジェクト: navam1915/Gw2Launcher
            /// <summary>
            /// Queries the volume controller for the process
            /// </summary>
            /// <returns>True if found</returns>
            public bool Query()
            {
                if (!isSupported)
                {
                    return(false);
                }

                IAudioSessionEnumerator sessionEnumerator = null;

                try
                {
                    mgr.GetSessionEnumerator(out sessionEnumerator);
                    int count;
                    sessionEnumerator.GetCount(out count);

                    for (int i = 0; i < count; i++)
                    {
                        IAudioSessionControl2 ctl;
                        sessionEnumerator.GetSession(i, out ctl);
                        int cpid;
                        ctl.GetProcessId(out cpid);

                        if (cpid == processId)
                        {
                            volume = ctl as ISimpleAudioVolume;
                            return(true);
                        }

                        Marshal.ReleaseComObject(ctl);
                    }
                }
                finally
                {
                    if (sessionEnumerator != null)
                    {
                        Marshal.ReleaseComObject(sessionEnumerator);
                    }
                }

                return(false);
            }
コード例 #9
0
ファイル: Program.cs プロジェクト: incryptx/CommandLineMedia
        /// <summary>
        /// Finds the matching process and volume control
        /// </summary>
        /// <param name="processName">The name of the process to find</param>
        /// <param name="selectedProcess">The selected process</param>
        /// <param name="volumeControl">The volume control object</param>
        private static void FindMatchingProcess(string processName, out Process selectedProcess, out ISimpleAudioVolume volumeControl)
        {
            selectedProcess = null;
            volumeControl   = null;

            // First find the list of matching processes
            Process[] matchingProcesses = Process.GetProcessesByName(processName);

            if (matchingProcesses != null && matchingProcesses.Length > 0)
            {
                // Attempt to see if we can find an audio session with the same Process ID as one we have found
                IMMDeviceEnumerator     deviceEnumerator  = null;
                IMMDevice               device            = null;
                IAudioSessionManager2   sessionManager    = null;
                IAudioSessionEnumerator sessionEnumerator = null;
                object activatedObject    = null;
                Guid   sessionManagerGuid = typeof(IAudioSessionManager2).GUID;

                try
                {
                    // Create the Device Enumerator
                    deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());

                    // Get the default audio device
                    if (deviceEnumerator != null)
                    {
                        deviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia, out device);
                    }

                    // Get the Session Manager
                    if (device != null)
                    {
                        device.Activate(ref sessionManagerGuid, (uint)0, IntPtr.Zero, out activatedObject);
                        sessionManager  = activatedObject as IAudioSessionManager2;
                        activatedObject = null;
                    }

                    // Get the Session Enumerator
                    if (sessionManager != null)
                    {
                        sessionManager.GetSessionEnumerator(out sessionEnumerator);
                    }

                    // Look through the list of Sessions and find one with a matching process ID.
                    if (sessionEnumerator != null)
                    {
                        int totalSessions = 0;

                        sessionEnumerator.GetCount(out totalSessions);

                        for (int currentSession = 0; currentSession < totalSessions; currentSession++)
                        {
                            IAudioSessionControl currentSessionControl = null;

                            sessionEnumerator.GetSession(currentSession, out currentSessionControl);

                            IAudioSessionControl2 currentSessionControl2 = currentSessionControl as IAudioSessionControl2;

                            if (currentSessionControl2 != null)
                            {
                                uint processID = 0;

                                currentSessionControl2.GetProcessID(out processID);

                                foreach (Process currentProcess in matchingProcesses)
                                {
                                    // We found the correct process and audio session
                                    if (currentProcess.Id == processID)
                                    {
                                        selectedProcess = currentProcess;
                                        volumeControl   = currentSessionControl as ISimpleAudioVolume;
                                        break;
                                    }
                                }
                            }

                            if (selectedProcess != null)
                            {
                                // We found the volume control
                                break;
                            }
                            else
                            {
                                // Free the current session
                                Marshal.ReleaseComObject(currentSessionControl);
                            }
                        }
                    }
                }
                finally
                {
                    // Clean up the COM Objects that we used

                    if (activatedObject != null)
                    {
                        Marshal.ReleaseComObject(activatedObject);
                    }

                    if (sessionEnumerator != null)
                    {
                        Marshal.ReleaseComObject(sessionEnumerator);
                    }

                    if (sessionManager != null)
                    {
                        Marshal.ReleaseComObject(sessionManager);
                    }

                    if (device != null)
                    {
                        Marshal.ReleaseComObject(device);
                    }

                    if (deviceEnumerator != null)
                    {
                        Marshal.ReleaseComObject(deviceEnumerator);
                    }
                }

                // If we get here for some reason and don't have a matching process then we will just take the first one with a valid Window Handle
                if (selectedProcess == null)
                {
                    foreach (Process currentProcess in matchingProcesses)
                    {
                        if (currentProcess != null && currentProcess.MainWindowHandle != IntPtr.Zero)
                        {
                            selectedProcess = currentProcess;
                            break;
                        }
                    }
                }
            }
        }
コード例 #10
0
        private static ISimpleAudioVolume GetVolumeObject(int pid)
        {
            IMMDeviceEnumerator     deviceEnumerator  = null;
            IAudioSessionEnumerator sessionEnumerator = null;
            IAudioSessionManager2   mgr = null;
            IMMDevice speakers          = null;

            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
                ISimpleAudioVolume volumeControl = null;
                for (int i = 0; i < count; ++i)
                {
                    IAudioSessionControl2 ctl = null;
                    try
                    {
                        sessionEnumerator.GetSession(i, out ctl);

                        // NOTE: we could also use the app name from ctl.GetDisplayName()
                        int cpid;
                        ctl.GetProcessId(out cpid);

                        if (cpid == pid)
                        {
                            volumeControl = ctl as ISimpleAudioVolume;
                            break;
                        }
                    }
                    finally
                    {
                        //if (ctl != null) Marshal.ReleaseComObject(ctl);
                    }
                }

                return(volumeControl);
            }
            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);
                }
            }
        }
コード例 #11
0
        public static List <int> getAllAudioSessions()
        {
            List <int> pipNumbersList = new List <int>();

            IMMDeviceEnumerator     deviceEnumerator  = null;
            IAudioSessionEnumerator sessionEnumerator = null;
            IAudioSessionManager2   mgr = null;
            IMMDevice speakers          = null;

            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);

                for (int i = 0; i < count; ++i)
                {
                    IAudioSessionControl2 ctl = null;
                    try
                    {
                        sessionEnumerator.GetSession(i, out ctl);

                        // NOTE: we could also use the app name from ctl.GetDisplayName()
                        int cpid;
                        ctl.GetProcessId(out cpid);
                        pipNumbersList.Add(cpid);
                        //Console.WriteLine(cpid.ToString());
                    }
                    finally
                    {
                        //  if (ctl != null) Marshal.ReleaseComObject(ctl);
                    }
                }
                return(pipNumbersList);
            }
            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);
                }
            }
        }
コード例 #12
0
        //считывает текущее значение уровней звука и обновляет UI
        public void UpdateVisualizer()
        {
            if (speakers == null)
            {
                return;
            }

            IAudioSessionManager2   mgr = null;
            IAudioSessionEnumerator sessionEnumerator = null;
            IAudioSessionControl    ctl   = null;
            IAudioSessionControl2   ctl2  = null;
            IAudioMeterInformation  meter = null;

            try
            {
                // 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);

                float max_val = 0.0f;          //максимальное значение уровня звука для всех сессий
                int   h_min = 50, h_max = 120; //макс. и мин. значение высоты для эллипса

                int   hr;
                uint  pid = 0;
                float val = 0.0f;

                for (int i = 0; i < count; i++)
                {
                    if (ctl != null)
                    {
                        Marshal.ReleaseComObject(ctl); ctl = null;
                    }
                    if (ctl2 != null)
                    {
                        Marshal.ReleaseComObject(ctl2); ctl2 = null;
                    }
                    if (meter != null)
                    {
                        Marshal.ReleaseComObject(meter); meter = null;
                    }

                    //получаем WASAPI-сессию
                    hr = sessionEnumerator.GetSession(i, out ctl);
                    if (hr != 0)
                    {
                        continue;
                    }

                    ctl2 = (IAudioSessionControl2)ctl;
                    pid  = 0;
                    ctl2.GetProcessId(out pid);
                    if (pid != this_pid)
                    {
                        continue;                      //интересуют только сессии текущего процесса
                    }
                    meter = (IAudioMeterInformation)ctl;
                    hr    = meter.GetPeakValue(out val); //получаем уровень звука
                    if (hr != 0)
                    {
                        continue;
                    }
                    if (val > max_val)
                    {
                        max_val = val;
                    }
                }

                //изменяем высоту эллипса в соответствии со значением максимального уровня звука
                ellVisualizer.Height = h_min + max_val * (h_max - h_min);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), ex.GetType().ToString());
            }
            finally
            {
                //очистка ресурсов
                if (sessionEnumerator != null)
                {
                    Marshal.ReleaseComObject(sessionEnumerator); sessionEnumerator = null;
                }
                if (mgr != null)
                {
                    Marshal.ReleaseComObject(mgr); mgr = null;
                }

                if (ctl != null)
                {
                    Marshal.ReleaseComObject(ctl); ctl = null;
                }
                if (ctl2 != null)
                {
                    Marshal.ReleaseComObject(ctl2); ctl2 = null;
                }
                if (meter != null)
                {
                    Marshal.ReleaseComObject(meter); meter = null;
                }
            }
        }
コード例 #13
0
ファイル: VolumeManager.cs プロジェクト: otomarukanta/Norma
        private static ISimpleAudioVolume GetVolumeObject()
        {
            IMMDeviceEnumerator     deviceEnumerator  = null;
            IAudioSessionEnumerator sessionEnumerator = null;
            IAudioSessionManager2   sessionManager    = null;
            IMMDevice device = null;

            try
            {
                // ReSharper disable once SuspiciousTypeConversion.Global
                deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out device);

                // ReSharper disable once InconsistentNaming
                var    IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID;
                object obj;
                device.Activate(IID_IAudioSessionManager2, 0, IntPtr.Zero, out obj);
                sessionManager = (IAudioSessionManager2)obj;

                sessionManager.GetSessionEnumerator(out sessionEnumerator);
                int count;
                sessionEnumerator.GetCount(out count);

                ISimpleAudioVolume volumeControl = null;
                for (var i = 0; i < count; i++)
                {
                    IAudioSessionControl  sessionControl  = null;
                    IAudioSessionControl2 sessionControl2 = null;
                    try
                    {
                        sessionEnumerator.GetSession(i, out sessionControl);
                        sessionControl2 = sessionControl as IAudioSessionControl2;

                        if (sessionControl2 == null)
                        {
                            // 多分通らない
                            string displayName;
                            sessionControl.GetDisplayName(out displayName);
                            if (displayName == "Norma")
                            {
                                volumeControl = sessionControl as ISimpleAudioVolume;
                                break;
                            }
                        }
                        else
                        {
                            uint processId;
                            sessionControl2.GetProcessId(out processId);
                            if (processId == Process.GetCurrentProcess().Id)
                            {
                                volumeControl = sessionControl2 as ISimpleAudioVolume;
                                break;
                            }
                        }
                    }
                    finally
                    {
                        // うーん

                        /*
                         * if (sessionControl != null)
                         *  Marshal.ReleaseComObject(sessionControl);
                         * if (sessionControl2 != null)
                         *  Marshal.ReleaseComObject(sessionControl2);
                         */
                    }
                }
                return(volumeControl);
            }
            finally
            {
                if (sessionEnumerator != null)
                {
                    Marshal.ReleaseComObject(sessionEnumerator);
                }
                if (sessionManager != null)
                {
                    Marshal.ReleaseComObject(sessionManager);
                }
                if (device != null)
                {
                    Marshal.ReleaseComObject(device);
                }
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }
        }
コード例 #14
0
        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);
                }
            }
        }
コード例 #15
0
        /// <summary>
        /// 判断是否存在进程
        /// </summary>
        /// <param name="processName"></param>
        /// <returns></returns>
        public static bool IsExistProcessName(string processName)
        {
            try
            {
                //标识
                bool flag = false;
                // get the speakers (1st render + multimedia) device
                IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
                IMMDevice           speakers         = null;
                if (deviceEnumerator != null)
                {
                    deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);
                }

                // activate the session manager. we need the enumerator
                Guid   IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID;
                object o = null;

                if (speakers != null)
                {
                    speakers.Activate(ref IID_IAudioSessionManager2, 0, IntPtr.Zero, out o);
                }

                IAudioSessionManager2 mgr = (IAudioSessionManager2)o;
                // enumerate sessions for on this device
                IAudioSessionEnumerator sessionEnumerator = null;
                if (mgr != null)
                {
                    mgr.GetSessionEnumerator(out sessionEnumerator);
                }

                int count = 0;

                if (sessionEnumerator != null)
                {
                    sessionEnumerator.GetCount(out count);
                }


                for (int i = 0; i < count; i++)
                {
                    IAudioSessionControl  ctl;
                    IAudioSessionControl2 ctl2;

                    sessionEnumerator.GetSession(i, out ctl);
                    ctl2 = ctl as IAudioSessionControl2;

                    uint pid = 0;

                    string sout1 = "";
                    string sout2 = "";
                    int    a     = 0;


                    if (ctl2 != null)
                    {
                        ctl2.GetSessionIdentifier(out sout1);
                        ctl2.GetProcessId(out pid);
                        ctl2.GetSessionInstanceIdentifier(out sout2);
                    }


                    if (sout2.ToUpper().Contains(processName.ToUpper()))
                    {
                        ISimpleAudioVolume volumeControl = null;
                        volumeControl = ctl as ISimpleAudioVolume;
                        Guid guid = Guid.Empty;

                        AudioSessionState state;
                        ctl2.GetState(out state);
                        if (state.ToString() == "AudioSessionStateActive")
                        {
                            //volumeControl.GetMasterVolume(out Ad_Volume_level);
                            flag = true;
                        }
                    }

                    if (ctl != null)
                    {
                        Marshal.ReleaseComObject(ctl);
                    }

                    if (ctl2 != null)
                    {
                        Marshal.ReleaseComObject(ctl2);
                    }
                }

                if (sessionEnumerator != null)
                {
                    Marshal.ReleaseComObject(sessionEnumerator);
                }

                if (mgr != null)
                {
                    Marshal.ReleaseComObject(mgr);
                }

                if (speakers != null)
                {
                    Marshal.ReleaseComObject(speakers);
                }

                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
                return(flag);
            }
            catch (Exception ex)
            {
                WriteLog.WriteErrorLogToFile(string.Format("日志定位Controller.cs-IsExistProcessName(string processName)判断是否存在进程错误-错误信息:{0} {1}", ex.Message.ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), true);
                throw ex;
            }
        }
コード例 #16
0
 // enumerate sessions for on this device
 private static void GetSessionEnumerator(IAudioSessionManager2 mgr, out IAudioSessionEnumerator sessionEnumerator, out int count)
 {
     mgr.GetSessionEnumerator(out sessionEnumerator);
     sessionEnumerator.GetCount(out count);
 }
コード例 #17
0
        private static ISimpleAudioVolume GetVolumeObject(int pid)
        {
            IMMDeviceEnumerator     deviceEnumerator  = null;
            IAudioSessionEnumerator sessionEnumerator = null;
            IAudioSessionManager2   mgr = null;
            IMMDevice speakers          = null;

            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
                ISimpleAudioVolume volumeControl = null;
                for (int i = 0; i < count; ++i)
                {
                    IAudioSessionControl2 ctl = null;
                    try
                    {
                        sessionEnumerator.GetSession(i, out ctl);

                        // NOTE: we could also use the app name from ctl.GetDisplayName()
                        int cpid;
                        ctl.GetProcessId(out cpid);

                        if (cpid == pid)
                        {
                            volumeControl = ctl as ISimpleAudioVolume;
                            break;
                        }
                    }
                    finally
                    {
                        if (ctl != null)
                        {
                            Marshal.ReleaseComObject(ctl);
                        }
                    }
                }

                return(volumeControl);
            }
            finally
            {
                // bp2008 note: it may be necessary to swap the release of [sessionEnumerator] and [speakers], but that is based on a fork of the class that bloats the code by removing the GetVolumeObject method and copy pasting all that boilerplate into each method, so my faith is extremely limited.
                if (sessionEnumerator != null)
                {
                    Marshal.ReleaseComObject(sessionEnumerator);
                }
                if (mgr != null)
                {
                    Marshal.ReleaseComObject(mgr);
                }
                if (speakers != null)
                {
                    Marshal.ReleaseComObject(speakers);
                }
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }
        }
コード例 #18
0
        public static void SetApplicationMute(string procname, bool mute)
        {
            IAudioSessionManager2   mgr = null;
            IAudioSessionEnumerator sessionEnumerator = null;

            try
            {
                ISimpleAudioVolume obj = null;
                mgr = GetAudioSessionManager();
                if (mgr == null)
                {
                    return;
                }

                mgr.GetSessionEnumerator(out sessionEnumerator);
                int count;
                sessionEnumerator.GetCount(out count);

                for (int i = 0; i < count; i++)
                {
                    IAudioSessionControl ctl;
                    sessionEnumerator.GetSession(i, out ctl);
                    if (ctl == null)
                    {
                        continue;
                    }

                    IAudioSessionControl2 ctl2 = ctl as IAudioSessionControl2;
                    if (ctl2 != null)
                    {
                        try
                        {
                            if (new AudioSession(ctl2).Process.ProcessName.ToLower().Equals(procname))
                            {
                                obj = ctl2 as ISimpleAudioVolume;
                                if (mute)
                                {
                                    //obj.SetMute(mute, Guid.Empty);
                                    try
                                    {
                                        obj.GetMasterVolume(out volume); // Save old volume
                                    }
                                    catch (Exception e)
                                    {
                                    }
                                    obj.SetMasterVolume(0f, Guid.Empty);
                                }
                                else
                                {
                                    obj.SetMasterVolume(volume, Guid.Empty);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                }
                Marshal.ReleaseComObject(sessionEnumerator);
                Marshal.ReleaseComObject(mgr);
            }
            catch (Exception spotify_hire_me)
            {
                Console.WriteLine(spotify_hire_me);
            }
            finally
            {
                Marshal.ReleaseComObject(sessionEnumerator);
                Marshal.ReleaseComObject(mgr);
            }
            return;
        }