Exemple #1
0
        public static IMMDevice GetSpeakers()
        {
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice           speakers;

            deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);
            return(speakers);
        }
        //Up default audio device volume (0-100)
        public static bool AudioVolumeUp(int targetStep, bool inputDevice)
        {
            try
            {
                IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
                IMMDevice.IMMDevice deviceItem       = null;
                if (!inputDevice)
                {
                    deviceItem = deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
                }
                else
                {
                    deviceItem = deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia);
                }

                //Get the audio device volume endpoint
                deviceItem.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out object deviceActivated);
                IAudioEndpointVolume audioEndPointVolume = (IAudioEndpointVolume)deviceActivated;

                //Get the audio device volume
                audioEndPointVolume.GetMasterVolumeLevelScalar(out float volumeLevelCurrentFloat);
                float volumeLevelFloat = volumeLevelCurrentFloat + (targetStep / 100F);

                //Check the target volume
                if (volumeLevelFloat > 1.00)
                {
                    volumeLevelFloat = 1.00F;
                }
                if (volumeLevelFloat < 0.00)
                {
                    volumeLevelFloat = 0.00F;
                }

                //Change the audio device volume
                audioEndPointVolume.SetMasterVolumeLevelScalar(volumeLevelFloat, Guid.Empty);

                Debug.WriteLine("Up volume: " + targetStep + "% / " + volumeLevelFloat);
                return(true);
            }
            catch
            {
                Debug.WriteLine("Failed to up default audio device volume.");
                return(false);
            }
        }
        public IMMDevice GetDefaultDevice()
        {
            IMMDevice device = null;

            device_enumerator.GetDefaultAudioEndpoint(
                Vannatech.CoreAudio.Enumerations.EDataFlow.eRender,
                Vannatech.CoreAudio.Enumerations.ERole.eMultimedia, out device);
            return(device);
        }
Exemple #4
0
        /// <summary>
        /// Gets the default device for a given role and data flow.
        /// </summary>
        /// <param name="dataFlow">The data flow.</param>
        /// <param name="role">The device role.</param>
        /// <returns>The default device matching the data flow and role.</returns>
        internal static IMMDevice GetDefaultDevice(EDataFlow dataFlow, ERole role)
        {
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
            IMMDevice           device           = deviceEnumerator.GetDefaultAudioEndpoint(dataFlow, role);

            Marshal.ReleaseComObject(deviceEnumerator);

            return(device);
        }
Exemple #5
0
        /// <summary>
        /// Constructor
        /// </summary>

        public Volume()
        {
            const uint CLSCTX_INPROC_SERVER = 1;
            Guid       clsid        = new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E");
            Guid       IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");

            oEnumerator = null;
            uint hResult = CoCreateInstance(ref clsid, null, CLSCTX_INPROC_SERVER, ref IID_IUnknown, out oEnumerator);

            if (hResult != 0 || oEnumerator == null)
            {
                throw new Exception("CoCreateInstance() pInvoke failed");
            }
            iMde = oEnumerator as IMMDeviceEnumerator;
            if (iMde == null)
            {
                throw new Exception("COM cast failed to IMMDeviceEnumerator");
            }
            IntPtr pDevice = IntPtr.Zero;
            int    retVal  = iMde.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eConsole, ref pDevice);

            if (retVal != 0)
            {
                throw new Exception("IMMDeviceEnumerator.GetDefaultAudioEndpoint()");
            }
            int    dwStateMask = DEVICE_STATE_ACTIVE | DEVICE_STATE_NOTPRESENT | DEVICE_STATE_UNPLUGGED;
            IntPtr pCollection = IntPtr.Zero;

            retVal = iMde.EnumAudioEndpoints(EDataFlow.eRender, dwStateMask, ref pCollection);
            if (retVal != 0)
            {
                throw new Exception("IMMDeviceEnumerator.EnumAudioEndpoints()");
            }
            oDevice = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(pDevice);
            imd     = oDevice as IMMDevice;
            if (imd == null)
            {
                throw new Exception("COM cast failed to IMMDevice");
            }
            Guid   iid               = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A");
            uint   dwClsCtx          = (uint)CLSCTX.CLSCTX_ALL;
            IntPtr pActivationParams = IntPtr.Zero;
            IntPtr pEndPoint         = IntPtr.Zero;

            retVal = imd.Activate(ref iid, dwClsCtx, pActivationParams, ref pEndPoint);
            if (retVal != 0)
            {
                throw new Exception("IMMDevice.Activate()");
            }
            oEndPoint      = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(pEndPoint);
            iAudioEndpoint = oEndPoint as IAudioEndpointVolume;
            if (iAudioEndpoint == null)
            {
                throw new Exception("COM cast failed to IAudioEndpointVolume");
            }
        }
Exemple #6
0
        private static ISimpleAudioVolume GetVolumeObject(int pid)
        {
            // get the speakers (1st render + multimedia) device
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice           speakers;

            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);
            IAudioSessionManager2 mgr = (IAudioSessionManager2)o;

            // enumerate sessions for on this device
            IAudioSessionEnumerator sessionEnumerator;

            mgr.GetSessionEnumerator(out sessionEnumerator);
            int count;

            sessionEnumerator.GetCount(out count);

            // search for an audio session with the required name
            // NOTE: we could also use the process id instead of the app name (with IAudioSessionControl2)
            ISimpleAudioVolume volumeControl = null;

            for (int i = 0; i < count; i++)
            {
                IAudioSessionControl2 ctl;
                sessionEnumerator.GetSession(i, out ctl);
                int cpid;
                ctl.GetProcessId(out cpid);
                var processName = Process.GetProcessById(cpid).ProcessName;
                Console.WriteLine(processName);
            }
            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);
            }
            Marshal.ReleaseComObject(sessionEnumerator);
            Marshal.ReleaseComObject(mgr);
            Marshal.ReleaseComObject(speakers);
            Marshal.ReleaseComObject(deviceEnumerator);
            return(volumeControl);
        }
Exemple #7
0
        private void InitializeAudioDevice()
        {
            // Get default audio device
            MMDeviceEnumerator  deviceEnumeratorClass = new MMDeviceEnumerator();
            IMMDeviceEnumerator deviceEnumerator      = (IMMDeviceEnumerator)deviceEnumeratorClass;

            IMMDevice defaultDevice;

            deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out defaultDevice);

            // Log device name
            IPropertyStore store;

            defaultDevice.OpenPropertyStore(STGM.STGM_READ, out store);

            PROPVARIANT pv   = new PROPVARIANT();
            PropertyKey pkey = PKEY.PKEY_DeviceInterface_FriendlyName;

            store.GetValue(ref pkey, out pv);

            Debug.WriteLine("Using audio device '{0}'", pv.Value);

            // Retrieve IAudioClient
            Guid   iid     = new Guid(Constants.IID_IAudioClient);
            IntPtr propVar = IntPtr.Zero;
            object obj;

            defaultDevice.Activate(ref iid, CLSCTX.CLSCTX_ALL, ref propVar, out obj);

            this.audioClient = (IAudioClient)obj;

            // Get default format
            IntPtr defaultFormat;

            this.audioClient.GetMixFormat(out defaultFormat);
            this.UpdateWaveFormatInfo(defaultFormat);

            // Initialize IAudioClient
            Guid g = Guid.Empty;

            this.audioClient.Initialize(AUDCLNT_SHAREMODE.AUDCLNT_SHAREMODE_SHARED, (uint)AUDCLNT_STREAMFLAGS.AUDCLNT_STREAMFLAGS_EVENTCALLBACK, 0, 0, defaultFormat, ref g);
            this.audioClient.GetBufferSize(out this.wasapiBufferSize);
            this.audioClient.SetEventHandle(this.bufferReadyEvent.SafeWaitHandle.DangerousGetHandle());

            // Retrieve IAudioRenderClient
            iid = new Guid(Constants.IID_IAudioRenderClient);
            object ppv;

            this.audioClient.GetService(ref iid, out ppv);

            this.audioRenderClient = (IAudioRenderClient)ppv;

            // Start processing samples
            this.audioClient.Start();
        }
        //Set default audio device volume (0-100)
        public static bool AudioVolumeSet(int targetVolume, bool inputDevice)
        {
            try
            {
                IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
                IMMDevice.IMMDevice deviceItem       = null;
                if (!inputDevice)
                {
                    deviceItem = deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
                }
                else
                {
                    deviceItem = deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia);
                }

                //Get the audio device volume endpoint
                deviceItem.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out object deviceActivated);
                IAudioEndpointVolume audioEndPointVolume = (IAudioEndpointVolume)deviceActivated;

                //Check the target volume
                if (targetVolume > 100)
                {
                    targetVolume = 100;
                }
                if (targetVolume < 0)
                {
                    targetVolume = 0;
                }

                //Set the audio device volume
                float volumeLevelFloat = targetVolume / 100F;
                audioEndPointVolume.SetMasterVolumeLevelScalar(volumeLevelFloat, Guid.Empty);

                Debug.WriteLine("Set volume: " + targetVolume + "% / " + volumeLevelFloat);
                return(true);
            }
            catch
            {
                Debug.WriteLine("Failed to set default audio device volume.");
                return(false);
            }
        }
        private static ISimpleAudioVolume GetVolumeObject(int pid)
        {
            // get the speakers (1st render + multimedia) device
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice           speakers;

            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);
            IAudioSessionManager2 mgr = (IAudioSessionManager2)o;

            // enumerate sessions for on this device
            IAudioSessionEnumerator sessionEnumerator;

            mgr.GetSessionEnumerator(out sessionEnumerator);
            int count;

            sessionEnumerator.GetCount(out count);

            // search for an audio session with the required pid

            ISimpleAudioVolume volumeControl = null;

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


                sessionEnumerator.GetSession(i, out ctl);
                IAudioSessionControl2 ctl2 = ctl as IAudioSessionControl2;
                //uint pid;
                //ctl2.GetProcessId(out pid);
                //Process p = Process.GetProcessById((int)pid);
                // ctl2.SetDisplayName(p.ProcessName, Guid.Empty);
                uint npid;
                ctl2.GetProcessId(out npid);
                if (pid == npid)
                {
                    volumeControl = ctl2 as ISimpleAudioVolume;
                    break;
                }
                Marshal.ReleaseComObject(ctl);
                Marshal.ReleaseComObject(ctl2);
            }
            Marshal.ReleaseComObject(sessionEnumerator);
            Marshal.ReleaseComObject(mgr);
            Marshal.ReleaseComObject(speakers);
            Marshal.ReleaseComObject(deviceEnumerator);
            return(volumeControl);
        }
Exemple #10
0
        public static IEnumerable <string> EnumerateApplications()
        {
            // get the speakers (1st render + multimedia) device
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice           speakers;

            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);
            IAudioSessionManager2 mgr = (IAudioSessionManager2)o;

            // enumerate sessions for on this device
            IAudioSessionEnumerator sessionEnumerator;

            mgr.GetSessionEnumerator(out sessionEnumerator);
            int count;

            sessionEnumerator.GetCount(out count);

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

                sessionEnumerator.GetSession(i, out ctl);

                ctl2 = ctl as IAudioSessionControl2;

                if (ctl2 != null)
                {
                    uint   pid   = 0;
                    string sout1 = "";
                    string sout2 = "";

                    ctl2.GetSessionIdentifier(out sout1);
                    ctl2.GetProcessId(out pid);
                    ctl2.GetSessionInstanceIdentifier(out sout2);
                }

                string dn;
                ctl.GetDisplayName(out dn);
                yield return(dn);

                Marshal.ReleaseComObject(ctl);
            }
            Marshal.ReleaseComObject(sessionEnumerator);
            Marshal.ReleaseComObject(mgr);
            Marshal.ReleaseComObject(speakers);
            Marshal.ReleaseComObject(deviceEnumerator);
        }
        private static string GetDefaultDeviceId(IMMDeviceEnumerator deviceEnumerator, DataFlows dataFlow, DeviceRoles role)
        {
            IMMDevice _device = null;

            Marshal.ThrowExceptionForHR(deviceEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out _device));

            string ID;

            Marshal.ThrowExceptionForHR(_device.GetId(out ID));
            return(ID);
        }
Exemple #12
0
 private void Initialize()
 {
     if (deviceEnumerator == null)
     {
         deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
         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;
     }
 }
Exemple #13
0
 private static IMMDevice GetSpeakers()
 {
     // get the speakers (1st render + multimedia) device
     try {
         IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
         IMMDevice           speakers;
         deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);
         return(speakers);
     } catch {
         return(null);
     }
 }
Exemple #14
0
        public static ISimpleAudioVolume GetVolumeObject(int pid)
        {
            // Get the speakers (1st render + multimedia) device
            // ReSharper disable once SuspiciousTypeConversion.Global
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();

            deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.ERender, ERole.EMultimedia, out IMMDevice speakers);

            speakers.GetId(out string defaultDeviceId);

            ISimpleAudioVolume volumeControl = GetVolumeObject(pid, speakers);

            Marshal.ReleaseComObject(speakers);

            if (volumeControl == null)
            {
                // If volumeControl is null, then the process's volume object might be on a different device.
                // This happens if the process doesn't use the default device.
                //
                // As far as Spotify is concerned, if using the "--enable-audio-graph" command line argument,
                // a new option becomes available in the Settings that makes it possible to change the playback device.

                deviceEnumerator.EnumAudioEndpoints(EDataFlow.ERender, EDeviceState.Active, out IMMDeviceCollection deviceCollection);

                deviceCollection.GetCount(out int count);
                for (int i = 0; i < count; i++)
                {
                    deviceCollection.Item(i, out IMMDevice device);
                    device.GetId(out string deviceId);

                    try
                    {
                        if (deviceId == defaultDeviceId)
                        {
                            continue;
                        }

                        volumeControl = GetVolumeObject(pid, device);
                        if (volumeControl != null)
                        {
                            break;
                        }
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(device);
                    }
                }
            }

            Marshal.ReleaseComObject(deviceEnumerator);
            return(volumeControl);
        }
Exemple #15
0
        private static IMMDevice GetOutputDevice()
        {
            // get the speakers (1st render + multimedia) device
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice           speakers;

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

            Marshal.ReleaseComObject(deviceEnumerator);

            return(speakers);
        }
        private void AdjustMixerVolume()
        {
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
            IMMDevice           ppDevice;

            deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eConsole, out ppDevice);
            Guid   guid = typeof(IAudioSessionManager2).GUID;
            object ppInterface;

            ppDevice.Activate(ref guid, 0, IntPtr.Zero, out ppInterface);
            IAudioSessionManager2   audioSessionManager2 = (IAudioSessionManager2)ppInterface;
            IAudioSessionEnumerator SessionEnum;

            audioSessionManager2.GetSessionEnumerator(out SessionEnum);
            int SessionCount1;

            SessionEnum.GetCount(out SessionCount1);
            List <ISimpleAudioVolume> list = new List <ISimpleAudioVolume>();

            for (int SessionCount2 = 0; SessionCount2 < SessionCount1; ++SessionCount2)
            {
                IAudioSessionControl2 Session;
                SessionEnum.GetSession(SessionCount2, out Session);
                ulong pRetVal;
                Session.GetProcessId(out pRetVal);
                if ((long)pRetVal == (long)Process.GetCurrentProcess().Id)
                {
                    list.Add(Session as ISimpleAudioVolume);
                }
            }
            float fLevel = 1f;

            foreach (ISimpleAudioVolume simpleAudioVolume in list)
            {
                float pfLevel;
                simpleAudioVolume.GetMasterVolume(out pfLevel);
                if ((double)fLevel > (double)pfLevel)
                {
                    fLevel = pfLevel;
                }
            }
            foreach (ISimpleAudioVolume simpleAudioVolume in list)
            {
                Guid EventContext = Guid.Empty;
                simpleAudioVolume.SetMasterVolume(fLevel, ref EventContext);
                Marshal.ReleaseComObject(simpleAudioVolume);
            }
            Marshal.ReleaseComObject(SessionEnum);
            Marshal.ReleaseComObject(audioSessionManager2);
            Marshal.ReleaseComObject(ppDevice);
            Marshal.ReleaseComObject(deviceEnumerator);
        }
Exemple #17
0
        public static MMDevice GetDefaultDevice(DataFlow dataFlow, Role role = Role.Multimedia)
        {
            IMMDeviceEnumerator deviceEnumerator = null;
            IMMDevice           device;

            try {
                deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
                deviceEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out device);
                return(new MMDevice(device, role));
            } finally {
                ReleaseComObject(ref deviceEnumerator);
            }
        }
Exemple #18
0
        // Switches default device to current default devices. Doesn't change the device, but sends an event so the program needs to aquire the device again, this time using our hook.
        public static void switchDefaultDevice()
        {
            List <SoundInfoDevice> devices = getSoundInfo();

            if (devices.Count >= 2)
            {
                IMMDeviceEnumerator enumerator = (IMMDeviceEnumerator) new DeviceEnumerator();
                string id = enumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).GetId();

                IPolicyConfig policyConfig = (IPolicyConfig) new IPolicyConfigClass();
                policyConfig.SetDefaultEndpoint(id, ERole.eMultimedia);
            }
        }
Exemple #19
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="dataFlow"></param>
 /// <param name="role"></param>
 /// <returns></returns>
 /// <exception cref="COMException"></exception>
 /// <exception cref="DeviceNotFoundException">If there is no default device</exception>
 public MMDevice GetDefaultAudioEndpoint(DataFlow dataFlow, Role role)
 {
     try
     {
         IMMDevice _Device;
         Marshal.ThrowExceptionForHR(_realEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out _Device));
         return(new MMDevice(_Device));
     }
     catch (COMException comException) when(comException.ErrorCode == DeviceNotFoundException.E_NOTFOUND)
     {//if COMException will be used the same way in other methods consider create Exception Mapper instead of manual try/catch
         throw new DeviceNotFoundException("No devices found during default device detection", comException);
     }
 }
        static Dictionary <ISimpleAudioVolume, Process> EnumerateApplications()
        {
            Dictionary <ISimpleAudioVolume, Process> result = new Dictionary <ISimpleAudioVolume, Process>();

            // get the speakers (1st render + multimedia) device
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice           speakers;

            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);
            IAudioSessionManager2 mgr = (IAudioSessionManager2)o;

            // enumerate sessions for on this device
            IAudioSessionEnumerator sessionEnumerator;

            mgr.GetSessionEnumerator(out sessionEnumerator);
            int count;

            sessionEnumerator.GetCount(out count);

            for (int i = 0; i < count; i++)
            {
                IAudioSessionControl2 ctl;
                sessionEnumerator.GetSession(i, out ctl);
                uint dd = 0;
                var  r  = ctl.GetProcessId(out dd);
                if (r == 0)
                {
                    var process = GetProcessById((int)dd);
                    if (process != null)
                    {
                        result.Add(ctl as ISimpleAudioVolume, process);
                    }
                    else
                    {
                        Marshal.ReleaseComObject(ctl);
                    }
                }
            }
            Marshal.ReleaseComObject(sessionEnumerator);
            Marshal.ReleaseComObject(mgr);
            Marshal.ReleaseComObject(speakers);
            Marshal.ReleaseComObject(deviceEnumerator);

            return(result);
        }
Exemple #21
0
        public VolumeMaster()
        {
            // get the speakers (1st render + multimedia) device
            List <AudioSession> list             = new List <AudioSession>();
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
            IMMDevice           speakers;

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

            Guid   GUID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID;
            object o;

            speakers.Activate(ref GUID_IAudioSessionManager2, 0, IntPtr.Zero, out o);
            IAudioSessionManager2 mgr = (IAudioSessionManager2)o;

            if (mgr == null)
            {
                Sessions = list;
                return;
            }

            IAudioSessionEnumerator sessionEnumerator;

            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)
                {
                    list.Add(new AudioSession(ctl2));
                }
            }
            Marshal.ReleaseComObject(speakers);
            Marshal.ReleaseComObject(deviceEnumerator);
            Marshal.ReleaseComObject(sessionEnumerator);
            Marshal.ReleaseComObject(mgr);

            Sessions = list;
        }
        void RefreshDevices()
        {
            lock (this)
            {
                IMMDeviceCollection IMMDeviceCollection;
                _IMMDeviceEnumerator.EnumAudioEndpoints(EDataFlow.eRender, 0xF, out IMMDeviceCollection);
                uint deviceCount = 0;
                IMMDeviceCollection.GetCount(out deviceCount);

                for (uint n = 0; n < deviceCount; n++)
                {
                    IMMDevice IMMDevice;
                    IMMDeviceCollection.Item(n, out IMMDevice);
                    string uid = "";
                    IMMDevice.GetId(out uid);
                    if (!_PlaybackDevices.ContainsKey(uid))
                    {
                        _PlaybackDevices.Add(uid, new PlaybackDevice_WindowsCoreApi(IMMDevice));
                    }
                }

                {
                    IMMDevice Default;
                    _IMMDeviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, 0x0, out Default);
                    string uid = "";
                    Default.GetId(out uid);
                    if (!_PlaybackDevices.ContainsKey(uid))
                    {
                        _PlaybackDevices.Add(uid, new PlaybackDevice_WindowsCoreApi(Default));
                    }
                    _PlaybackDevices[uid]._Default = true;
                }

                _IMMDeviceEnumerator.EnumAudioEndpoints(EDataFlow.eCapture, 0xF, out IMMDeviceCollection);

                deviceCount = 0;
                IMMDeviceCollection.GetCount(out deviceCount);

                for (uint n = 0; n < deviceCount; n++)
                {
                    IMMDevice IMMDevice;
                    IMMDeviceCollection.Item(n, out IMMDevice);
                    string uid = "";
                    IMMDevice.GetId(out uid);
                    if (!_RecordingDevices.ContainsKey(uid))
                    {
                        _RecordingDevices.Add(uid, new RecordingDevice_WindowsCoreApi(IMMDevice));
                    }
                }
            }
        }
Exemple #23
0
        /// <summary>
        /// 指示系统当前是否在播放声音
        /// </summary>
        /// <returns></returns>
        public static bool IsWindowsPlayingSound()
        {
            IMMDeviceEnumerator    enumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice              speakers   = enumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
            IAudioMeterInformation meter      = (IAudioMeterInformation)speakers.Activate(typeof(IAudioMeterInformation).GUID, 0, IntPtr.Zero);
            float value = meter.GetPeakValue();

            // this is a bit tricky. 0 is the official "no sound" value
            // but for example, if you open a video and plays/stops with it (w/o killing the app/window/stream),
            // the value will not be zero, but something really small (around 1E-09)
            // so, depending on your context, it is up to you to decide
            // if you want to test for 0 or for a small value
            return(value > 1E-08);
        }
Exemple #24
0
 public IAudioDevice GetDefaultDevice(ERole eRole = ERole.eMultimedia)
 {
     try
     {
         var rawDevice = _enumerator.GetDefaultAudioEndpoint(Flow, ERole.eMultimedia);
         _devices.TryFind(rawDevice.GetId(), out var device);
         return(device);
     }
     catch (Exception ex) when(ex.Is(HRESULT.ERROR_NOT_FOUND))
     {
         // Expected.
         return(null);
     }
 }
Exemple #25
0
        private static ISimpleAudioVolume GetVolumeObject(uint name)
        {
            // get the speakers (1st render + multimedia) device
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice           speakers;

            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);
            IAudioSessionManager2 mgr = (IAudioSessionManager2)o;

            // enumerate sessions for on this device
            IAudioSessionEnumerator sessionEnumerator;

            mgr.GetSessionEnumerator(out sessionEnumerator);
            int count;

            sessionEnumerator.GetCount(out count);

            // search for an audio session with the required name
            // NOTE: we could also use the process id instead of the app name (with IAudioSessionControl2)
            ISimpleAudioVolume volumeControl = null;

            for (int i = 0; i < count; i++)
            {
                IAudioSessionControl ctl1;
                sessionEnumerator.GetSession(i, out ctl1);
                var  ctl = ctl1 as IAudioSessionControl2;
                uint id;
                ctl.GetProcessId(out id);
                //string dn;
                //ctl.GetDisplayName(out dn);
                //if (string.Compare(name, dn, StringComparison.OrdinalIgnoreCase) == 0)
                if (id == name)
                {
                    volumeControl = ctl as ISimpleAudioVolume;
                    break;
                }
                Marshal.ReleaseComObject(ctl);
            }
            Marshal.ReleaseComObject(sessionEnumerator);
            Marshal.ReleaseComObject(mgr);
            Marshal.ReleaseComObject(speakers);
            Marshal.ReleaseComObject(deviceEnumerator);
            return(volumeControl);
        }
Exemple #26
0
        /// <summary>
        /// Get Default Endpoint
        /// </summary>
        /// <param name="dataFlow">Data Flow</param>
        /// <param name="role">Role</param>
        /// <returns>Device</returns>
        public MMDevice GetDefaultAudioEndpoint(DataFlow dataFlow, Role role)
        {
            var hresult = _mmDeviceEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out var device);

            const int E_NOTFOUND = unchecked ((int)0x80070490);

            if (hresult == E_NOTFOUND)
            {
                return(null);
            }

            Marshal.ThrowExceptionForHR(hresult);
            return(new MMDevice(device));
        }
Exemple #27
0
        public MMDevice GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role)
        {
            IMMDevice result;

            try
            {
                Marshal.ThrowExceptionForHR(_realEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out result));
                return(CreateMMDevice(result));
            }
            catch (Exception e)
            {
                return(null);
            }
        }
        private static ISimpleAudioVolume GetVolumeObject(int pid)
        {
            IMMDeviceEnumerator     iMMDeviceEnumerator = null;
            IAudioSessionEnumerator SessionEnum         = null;
            IAudioSessionManager2   audioSessionManager = null;
            IMMDevice ppDevice = null;

            try
            {
                iMMDeviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
                iMMDeviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out ppDevice);
                Guid iid = typeof(IAudioSessionManager2).GUID;
                ppDevice.Activate(ref iid, 0, IntPtr.Zero, out object ppInterface);
                audioSessionManager = (IAudioSessionManager2)ppInterface;
                audioSessionManager.GetSessionEnumerator(out SessionEnum);
                SessionEnum.GetCount(out int SessionCount);
                ISimpleAudioVolume result = null;
                for (int i = 0; i < SessionCount; i++)
                {
                    IAudioSessionControl2 Session = null;
                    SessionEnum.GetSession(i, out Session);
                    Session.GetProcessId(out int pRetVal);
                    if (pRetVal == pid)
                    {
                        result = (Session as ISimpleAudioVolume);
                        break;
                    }
                }
                return(result);
            }
            finally
            {
                if (SessionEnum != null)
                {
                    Marshal.ReleaseComObject(SessionEnum);
                }
                if (audioSessionManager != null)
                {
                    Marshal.ReleaseComObject(audioSessionManager);
                }
                if (ppDevice != null)
                {
                    Marshal.ReleaseComObject(ppDevice);
                }
                if (iMMDeviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(iMMDeviceEnumerator);
                }
            }
        }
Exemple #29
0
        public static AudioSessionControl [] GetAudioSessionControls()
        {
            // get the speakers (1st render + multimedia) device
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice           speakers;

            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);
            IAudioSessionManager2 mgr = (IAudioSessionManager2)o;

            // enumerate sessions for on this device
            IAudioSessionEnumerator sessionEnumerator;

            mgr.GetSessionEnumerator(out sessionEnumerator);
            int count;

            sessionEnumerator.GetCount(out count);
            AudioSessionControl[] audio_session_controls = new AudioSessionControl[count];
            for (int control_index = 0; control_index < count; control_index++)
            {
                IAudioSessionControl2 ctl;
                sessionEnumerator.GetSession(control_index, out ctl);
                string display_name;
                string icon_path;
                int    process_id;
                string session_identifier;
                string session_instance_identifier;


                ctl.GetDisplayName(out display_name);
                ctl.GetIconPath(out icon_path);
                ctl.GetProcessId(out process_id);
                ctl.GetSessionIdentifier(out session_identifier);
                ctl.GetSessionInstanceIdentifier(out session_instance_identifier);
                audio_session_controls[control_index] = new AudioSessionControl(display_name, icon_path, process_id, session_identifier, session_instance_identifier);

                Marshal.ReleaseComObject(ctl);
            }
            Marshal.ReleaseComObject(sessionEnumerator);
            Marshal.ReleaseComObject(mgr);
            Marshal.ReleaseComObject(speakers);
            Marshal.ReleaseComObject(deviceEnumerator);
            return(audio_session_controls);
        }
Exemple #30
0
        private static ISimpleAudioVolume GetVolumeObject(int pid)
        {
            // get the speakers (1st render + multimedia) device
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice           speakers;

            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);
            IAudioSessionManager2 mgr = (IAudioSessionManager2)o;

            // enumerate sessions for on this device
            IAudioSessionEnumerator sessionEnumerator;

            mgr.GetSessionEnumerator(out sessionEnumerator);
            int count;

            sessionEnumerator.GetCount(out count);

            uint val;

            ISimpleAudioVolume volumeControl = null;

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

                IAudioSessionControl2 ctl2 = (IAudioSessionControl2)ctl;
                ctl2.GetProcessId(out val);

                if (val == pid)
                {
                    volumeControl = ctl as ISimpleAudioVolume;
                    break;
                }
                Marshal.ReleaseComObject(ctl);
                Marshal.ReleaseComObject(ctl2);
            }
            Marshal.ReleaseComObject(sessionEnumerator);
            Marshal.ReleaseComObject(mgr);
            Marshal.ReleaseComObject(speakers);
            Marshal.ReleaseComObject(deviceEnumerator);
            return(volumeControl);
        }
            private static int GetDefaultAudioEndpoint(IMMDeviceEnumerator self, DataFlow dataflow, Role role,
                out IntPtr ppendpoint)
            {
                var entryPoint = HookRuntimeInfo.Callback as EntryPoint;

                if (entryPoint == null || entryPoint.Interface == null)
                    return self.GetDefaultAudioEndpoint(dataflow, role, out ppendpoint);

                var remoteInterface = entryPoint.Interface;

                try
                {
                    var devId = remoteInterface.GetDefaultDevice(dataflow, role);
                    return self.GetDevice(devId, out ppendpoint);
                }
                catch (Exception ex)
                {
                    remoteInterface.ReportError(RemoteHooking.GetCurrentProcessId(), ex);
                    //Something failed so return the actual default device
                    return self.GetDefaultAudioEndpoint(dataflow, role, out ppendpoint);
                }
            }
        //public event MixerChangedEventHandler MixerChanged;



        #region Class Constructor and Dispose public methods

        /// <summary>

        /// Constructor

        /// </summary>

        public EndpointVolume()
        {

            const uint CLSCTX_INPROC_SERVER = 1;

            Guid clsid = new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E");

            Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");

            oEnumerator = null;

            uint hResult = CoCreateInstance(ref clsid, null, CLSCTX_INPROC_SERVER, ref IID_IUnknown, out oEnumerator);

            if (hResult != 0 || oEnumerator == null)
            {

                throw new Exception("CoCreateInstance() pInvoke failed");

            }

            iMde = oEnumerator as IMMDeviceEnumerator;

            if (iMde == null)
            {

                throw new Exception("COM cast failed to IMMDeviceEnumerator");

            }

            IntPtr pDevice = IntPtr.Zero;

            int retVal = iMde.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eConsole, ref pDevice);

            if (retVal != 0)
            {

                throw new Exception("IMMDeviceEnumerator.GetDefaultAudioEndpoint()");

            }

            int dwStateMask = DEVICE_STATE_ACTIVE | DEVICE_STATE_NOTPRESENT | DEVICE_STATE_UNPLUGGED;

            IntPtr pCollection = IntPtr.Zero;

            retVal = iMde.EnumAudioEndpoints(EDataFlow.eRender, dwStateMask, ref pCollection);

            if (retVal != 0)
            {

                throw new Exception("IMMDeviceEnumerator.EnumAudioEndpoints()");

            }

            oDevice = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(pDevice);

            imd = oDevice as IMMDevice;

            if (imd == null)
            {

                throw new Exception("COM cast failed to IMMDevice");

            }

            Guid iid = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A");

            uint dwClsCtx = (uint)CLSCTX.CLSCTX_ALL;

            IntPtr pActivationParams = IntPtr.Zero;

            IntPtr pEndPoint = IntPtr.Zero;

            retVal = imd.Activate(ref iid, dwClsCtx, pActivationParams, ref pEndPoint);

            if (retVal != 0)
            {

                throw new Exception("IMMDevice.Activate()");

            }

            oEndPoint = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(pEndPoint);

            iAudioEndpoint = oEndPoint as IAudioEndpointVolume;

            if (iAudioEndpoint == null)
            {

                throw new Exception("COM cast failed to IAudioEndpointVolume");

            }

            /*

            delMixerChange = new DelegateMixerChange(MixerChange);

            retVal = iAudioEndpoint.RegisterControlChangeNotify(delMixerChange);

            if (retVal != 0)

            {

            throw new Exception("iAudioEndpoint.RegisterControlChangeNotify(delMixerChange)");

            }

            */

        }