private static IMMDeviceEnumerator GetCOMEnumerator()
        {
            MMDeviceEnumerator  comObj           = new MMDeviceEnumerator();
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)comObj;

            return(deviceEnumerator);
        }
Exemple #2
0
        /// <summary>
        /// Tries to set the volume to a specified level
        /// </summary>
        /// <returns>returns true if the keypress was sent, false if there was an error</returns>
        public bool SetVolume(int Volume)
        {
            try
            {
                IMMDeviceEnumerator enumerator = MMDeviceEnumeratorFactory.CreateInstance();
                IMMDevice           device;

                int eRender     = 0;
                int eMultimedia = 1;

                enumerator.GetDefaultAudioEndpoint(eRender, eMultimedia, out device);

                object endpoint = null;
                device.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out endpoint);

                IAudioEndpointVolume audio = (IAudioEndpointVolume)endpoint;

                if (audio.SetMasterVolumeLevelScalar(Volume / 100f, new Guid()) != 0)
                {
                    throw new Exception();
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemple #3
0
        /// <summary>
        /// Tries to get the currently set volume
        /// </summary>
        /// <returns>either the current audio volume or null if the level could not be read</returns>
        public Nullable <int> GetCurrentVolume()
        {
            try
            {
                float level = 0;

                IMMDeviceEnumerator enumerator = MMDeviceEnumeratorFactory.CreateInstance();
                IMMDevice           device;

                int eRender     = 0;
                int eMultimedia = 1;

                enumerator.GetDefaultAudioEndpoint(eRender, eMultimedia, out device);

                object endpoint = null;
                device.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out endpoint);

                IAudioEndpointVolume audio = (IAudioEndpointVolume)endpoint;

                audio.GetMasterVolumeLevelScalar(ref level);

                return((int)(level * 100));
            }
            catch
            {
                return(null);
            }
        }
        //Get default audio device mute status
        public static bool AudioMuteGetStatus(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 current mute status
                audioEndPointVolume.GetMute(out bool muteStatus);
                return(muteStatus);
            }
            catch
            {
                //Debug.WriteLine("Failed to get mute status.");
                return(false);
            }
        }
        private void InitializeAudio(AudioDataFlow audioFlow, IMMDeviceEnumerator deviceEnumerator)
        {
            //Get Audio Device
            COMResult result = deviceEnumerator.GetDefaultAudioEndpoint(audioFlow, EndPointRole.eMultimedia, out _audioDevice);

            //Register End point notification
            _notifyClient = new MMNotificationClient();
            result        = deviceEnumerator.RegisterEndpointNotificationCallback(_notifyClient);
            //Get Audio Client from device
            result       = _audioDevice.Activate(typeof(IAudioClient).GUID, 0, IntPtr.Zero, out object obj);
            _audioClient = (IAudioClient)obj;
            //Get Audio Meter from device
            result      = _audioDevice.Activate(typeof(IAudioMeterInformation).GUID, 0, IntPtr.Zero, out obj);
            _audioMeter = (IAudioMeterInformation)obj;
            //Initialize Audio Client.
            _sessionGuid = new Guid();
            result       = _audioClient.GetMixFormat(out waveFormat);
            AudioClientStreamFlags streamFlag = AudioClientStreamFlags.None;

            if (audioFlow == AudioDataFlow.eRender)
            {
                streamFlag = AudioClientStreamFlags.Loopback;
            }
            result = _audioClient.Initialize(AudioClientMode.Shared, streamFlag, 10000000, 0, waveFormat, ref _sessionGuid);
            //Get Capture Client.
            result = _audioClient.GetService(typeof(IAudioCaptureClient).GUID, out obj);
            Marshal.ThrowExceptionForHR((int)result);
            _audioCaptureClient = (IAudioCaptureClient)obj;
            result = _audioClient.Start();
            //Change wave format here
            SetupWaveFormat(waveFormat);
        }
Exemple #6
0
        private static IAudioEndpointVolume GetMasterVolumeObject()
        {
            IMMDeviceEnumerator deviceEnumerator = null;
            IMmDevice           speakers         = null;

            try
            {
                deviceEnumerator = MmDeviceEnumeratorFactory.CreateInstance();
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.ERender, ERole.EMultimedia, out speakers);

                var    IID_IAudioEndpointVolume = typeof(IAudioEndpointVolume).GUID;
                object o;
                speakers.Activate(ref IID_IAudioEndpointVolume, 0, IntPtr.Zero, out o);
                IAudioEndpointVolume masterVol = (IAudioEndpointVolume)o;

                return(masterVol);
            }
            finally
            {
                if (speakers != null)
                {
                    Marshal.ReleaseComObject(speakers);
                }
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }
        }
        //Mute default audio device
        public static void AudioUnmute(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;

                //Set the switched mute status
                audioEndPointVolume.SetMute(false, Guid.Empty);
                Debug.WriteLine("Unmuted audio device.");
            }
            catch
            {
                Debug.WriteLine("Failed to unmute audio device.");
            }
        }
Exemple #8
0
        private static bool IsAudioInputDevice(string deviceId)
        {
            IMMDeviceCollection deviceCollection;
            IMMDevice           device;
            string id;
            bool   result = false;
            uint   count;

            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();

            deviceEnumerator.EnumAudioEndpoints(EDataFlow.eCapture, (uint)DeviceState.All, out deviceCollection);
            deviceCollection.GetCount(out count);
            Marshal.ReleaseComObject(deviceEnumerator);

            for (uint i = 0; i < count; i++)
            {
                deviceCollection.Item(i, out device);
                device.GetId(out id);
                Marshal.ReleaseComObject(device);
                if (deviceId == id)
                {
                    result = true;
                    break;
                }
            }
            if (deviceCollection != null)
            {
                Marshal.ReleaseComObject(deviceCollection);
            }
            return(result);
        }
        //Get the current default audio device
        public static AudioDeviceSummary GetDefaultDevice()
        {
            try
            {
                IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
                IMMDevice.IMMDevice deviceItem       = deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

                //Get the audio device id
                string deviceId = deviceItem.GetId();

                //Get the audio device name
                PropertyVariant propertyVariant = new PropertyVariant();
                IPropertyStore  propertyStore   = deviceItem.OpenPropertyStore(STGM.STGM_READ);
                propertyStore.GetValue(ref PKEY_Device_FriendlyName, out propertyVariant);
                string deviceName = Marshal.PtrToStringUni(propertyVariant.pwszVal);

                return(new AudioDeviceSummary()
                {
                    Identifier = deviceId, Name = deviceName
                });
            }
            catch
            {
                Debug.WriteLine("Failed to get the default audio device.");
                return(null);
            }
        }
Exemple #10
0
 public static int SetMicrophoneMasterVolume(float volume)
 {
     if (volume < 0 || volume > 1)
     {
         throw new ArgumentOutOfRangeException("Provide volumet between 0 and 1");
     }
     try
     {
         IMMDeviceEnumerator deviceEnumerator = MMDeviceEnumeratorFactory.CreateInstance();
         IMMDevice           microphone       = null;
         deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eCommunications, out microphone);
         if (microphone != null)
         {
             object aepv_obj;
             microphone.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out aepv_obj);
             IAudioEndpointVolume aepv = (IAudioEndpointVolume)aepv_obj;
             Guid ZeroGuid             = new Guid();
             int  res = aepv.SetMasterVolumeLevelScalar(volume, ZeroGuid);
             Console.WriteLine($"Audio microphone level set to {volume}%");
             return(res);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine($"**Could not set microphone level** {ex.Message}");
         return(ex.HResult);
     }
     return(1); // no mic
 }
Exemple #11
0
        public static bool?IsMicrophoneMute()
        {
            bool mute = false;

            try
            {
                IMMDeviceEnumerator deviceEnumerator = MMDeviceEnumeratorFactory.CreateInstance();
                IMMDevice           microphone       = null;
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eCommunications, out microphone);
                if (microphone != null)
                {
                    object aepv_obj;
                    microphone.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out aepv_obj);
                    IAudioEndpointVolume aepv = (IAudioEndpointVolume)aepv_obj;
                    int v   = 0;
                    int res = aepv.GetMute(out v);
                    mute = (v == 1);

                    Console.WriteLine($"Audio capture mute state is {mute}");
                    return(mute);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"**Could not read Audio capture mute state ** {ex.Message}");
            }
            return(null);
        }
Exemple #12
0
        public static int SetMicrophoneMute(bool mute)
        {
            try
            {
                IMMDeviceEnumerator deviceEnumerator = MMDeviceEnumeratorFactory.CreateInstance();
                IMMDevice           microphone       = null;
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eCommunications, out microphone);
                if (microphone != null)
                {
                    object aepv_obj;
                    microphone.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out aepv_obj);
                    IAudioEndpointVolume aepv = (IAudioEndpointVolume)aepv_obj;
                    Guid ZeroGuid             = new Guid();
                    int  v   = mute ? 1 : 0;
                    int  res = aepv.SetMute(v, ref ZeroGuid);

                    Console.WriteLine($"Audio mute is set to {mute}");
                    return(0);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"**Could not set Audio capture mute state** {ex.Message}");
                return(ex.HResult);
            }
            return(1); // no mic
        }
        public static bool IsVolumeMuted()
        {
            // get the speakers (1st render + multimedia) device
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice           speakers;
            const int           eRender     = 0;
            const int           eMultimedia = 1;

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

            object o;

            speakers.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out o);
            IAudioEndpointVolume aepv = (IAudioEndpointVolume)o;
            int isMuted = aepv.GetMute();

            Marshal.ReleaseComObject(aepv);
            Marshal.ReleaseComObject(speakers);
            Marshal.ReleaseComObject(deviceEnumerator);

            if (isMuted == 1)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #14
0
        public void SetAppAndSystemVolume(float volume, bool muted)
        {
            Guid guidEnumetator = typeof(IMMDeviceEnumerator).GUID;
            Guid guidManager    = typeof(IAudioSessionManager).GUID;
            Guid guidVolume     = typeof(IAudioEndpointVolume).GUID;

            CoCreateInstance(ref MMDeviceEnumerator, null, CLSCTX_ALL, ref guidEnumetator, out IUnknown _enumerater);
            IMMDeviceEnumerator enumerator = _enumerater as IMMDeviceEnumerator;

            enumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out IMMDevice endpoint);
            endpoint.Activate(ref guidManager, CLSCTX_ALL, IntPtr.Zero, out IUnknown _manager);
            endpoint.Activate(ref guidVolume, CLSCTX_ALL, IntPtr.Zero, out IUnknown _volume);
            IAudioSessionManager manager = _manager as IAudioSessionManager;

            manager.GetSimpleAudioVolume(Guid.Empty, false, out ISimpleAudioVolume processvolume);
            processvolume.GetMasterVolume(out float prevolume);
            if (prevolume != volume)
            {
                processvolume.SetMasterVolume(volume, Guid.Empty);
            }

            processvolume.SetMute(muted, Guid.Empty);
            IAudioEndpointVolume systemvolume = _volume as IAudioEndpointVolume;

            systemvolume.SetMasterVolumeLevelScalar(muted?0:1, Guid.Empty);
            systemvolume.SetMute(muted, Guid.Empty);
        }
        public AEDev(bool resetDevice = false)
        {
            IMMDevice _Device = null;

            if (resetDevice)
            {
                _devId = "";
            }

            _realEnumerator = new _AEDeviceEnumerator() as IMMDeviceEnumerator;
            try
            {
                if (String.IsNullOrEmpty(_devId))
                {
                    Marshal.ThrowExceptionForHR(_realEnumerator.GetDefaultAudioEndpoint(0, 1, out _Device));
                    Marshal.ThrowExceptionForHR(_Device.GetId(out _devId));
                }
                else
                {
                    Marshal.ThrowExceptionForHR(_realEnumerator.GetDevice(_devId, out _Device));
                }
                devstatus state;
                Marshal.ThrowExceptionForHR(_Device.GetState(out state));
                if (state != devstatus.DEVICE_STATE_ACTIVE)
                {
                    throw new ApplicationException($"audio device is not active ({state.ToString()})");
                }
                _RealDevice = _Device;
                object result;
                Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioEndpointVolume, CTX.ALL, IntPtr.Zero, out result));
                _AudioEndPointVolume = result as IAudioEndpointVolume;
                _CallBack            = new AudioEndpointVolumeCallback(this);
                Marshal.ThrowExceptionForHR(_AudioEndPointVolume.RegisterControlChangeNotify(_CallBack));
            }
            catch (Exception)
            {
                // Catch if no device is found or changed device
                try
                {
                    Marshal.ThrowExceptionForHR(_realEnumerator.GetDefaultAudioEndpoint(0, 1, out _Device));
                    Marshal.ThrowExceptionForHR(_Device.GetId(out _devId));
                    devstatus state;
                    Marshal.ThrowExceptionForHR(_Device.GetState(out state));
                    if (state != devstatus.DEVICE_STATE_ACTIVE)
                    {
                        throw new ApplicationException($"audio device is not active ({state.ToString()})");
                    }
                    _RealDevice = _Device;
                    object result;
                    Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioEndpointVolume, CTX.ALL, IntPtr.Zero, out result));
                    _AudioEndPointVolume = result as IAudioEndpointVolume;
                    _CallBack            = new AudioEndpointVolumeCallback(this);
                    Marshal.ThrowExceptionForHR(_AudioEndPointVolume.RegisterControlChangeNotify(_CallBack));
                }
                catch (Exception)
                {
                    // Catch if no device is found
                }
            }
        }
        //Get default audio device volume (0-100)
        public static int AudioVolumeGet(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);
                int volumeLevelInt = Convert.ToInt32(volumeLevelCurrentFloat * 100);

                //Debug.WriteLine("Current volume: " + volumeLevelInt + "%");
                return(volumeLevelInt);
            }
            catch
            {
                Debug.WriteLine("Failed to get default audio device volume.");
                return(-1);
            }
        }
Exemple #17
0
 private static void GetVolumeControls(out IMMDeviceEnumerator deviceEnumerator, out IMMDevice speakers, out IAudioSessionManager2 mgr, out IAudioSessionEnumerator sessionEnumerator, out int count)
 {
     GetDeviceEnumerator(out deviceEnumerator);
     GetSpeakers(deviceEnumerator, out speakers);
     GetSessionManager(speakers, out mgr);
     GetSessionEnumerator(mgr, out sessionEnumerator, out count);
 }
Exemple #18
0
        public void UpdateProcessList()
        {
            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDeviceCollection outputDevices    = null;
            IMMDeviceCollection inputDevices     = null;

            deviceEnumerator.EnumAudioEndpoints(EDataFlow.eRender, STATE.ACTIVE, out outputDevices);
            deviceEnumerator.EnumAudioEndpoints(EDataFlow.eCapture, STATE.ACTIVE, out inputDevices);

            uint inputDeviceCount  = 0;
            uint outputDeviceCount = 0;

            inputDevices.GetCount(out inputDeviceCount);
            outputDevices.GetCount(out outputDeviceCount);

            // Loop over every output device
            for (uint i = 0; i < outputDeviceCount; i++)
            {
                IMMDevice device;
                outputDevices.Item(i, out device);

                AudioDevice audioDevice = new AudioDevice(device);
                Mapper.Mapper.DevicesAndProcesses[audioDevice] = audioDevice.GetAllSessions();
            }
        }
         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;
                 sessionEnumerator.GetSession(i, out ctl);
                 string dn;
                 ctl.GetDisplayName(out dn);
                 yield return dn;
                 Marshal.ReleaseComObject(ctl);
             }
             Marshal.ReleaseComObject(sessionEnumerator);
             Marshal.ReleaseComObject(mgr);
             Marshal.ReleaseComObject(speakers);
             Marshal.ReleaseComObject(deviceEnumerator);
         }
Exemple #20
0
        private static IAudioEndpointVolume GetMasterVolumeObject()
        {
            IMMDeviceEnumerator deviceEnumerator = null;
            IMMDevice           speakers         = null;

            try
            {
                deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);

                Guid   IID_IAudioEndpointVolume = typeof(IAudioEndpointVolume).GUID;
                object o;
                if (speakers == null)
                {
                    return(null);
                }
                speakers.Activate(ref IID_IAudioEndpointVolume, 0, IntPtr.Zero, out o);
                IAudioEndpointVolume masterVol = (IAudioEndpointVolume)o;

                return(masterVol);
            }
            finally
            {
                if (speakers != null)
                {
                    Marshal.ReleaseComObject(speakers);
                }
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }
        }
Exemple #21
0
        // from simon mourier https://stackoverflow.com/a/31042902

        public static float GetMasterVolume()
        {
            float volume = 0;

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

            if (deviceEnumerator != null)
            {
                IMMDevice speakers;
                const int eRender     = 0;
                const int eMultimedia = 1;
                deviceEnumerator.GetDefaultAudioEndpoint(eRender, eMultimedia, out speakers);

                if (speakers != null)
                {
                    object o;
                    speakers.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out o);

                    if (o != null)
                    {
                        IAudioEndpointVolume aepv = (IAudioEndpointVolume)o;

                        if (aepv != null)
                        {
                            volume = aepv.GetMasterVolumeLevelScalar();
                            Marshal.ReleaseComObject(aepv);
                        }
                    }
                    Marshal.ReleaseComObject(speakers);
                }
                Marshal.ReleaseComObject(deviceEnumerator);
            }
            return(volume);
        }
Exemple #22
0
        /// <summary>
        /// 指示系统当前是否在播放声音
        /// </summary>
        /// <returns></returns>
        public static bool IsWindowsPlayingSound()
        {
            try
            {
                IMMDeviceEnumerator    enumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
                IMMDevice              speakers   = enumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
                IAudioMeterInformation meter      = (IAudioMeterInformation)speakers.Activate(typeof(IAudioMeterInformation).GUID, 0, IntPtr.Zero);
                if (meter != null)
                {
                    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);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ec)
            {
                LogHelper.Warning(ec.ToString());
                return(false);
            }
        }
Exemple #23
0
 public void Dispose()
 {
     try { Stop(); } catch { }
     lock (mutex)
     {
         Cleanup();
         if (audioClient != null)
         {
             Marshal.ReleaseComObject(audioClient); audioClient = null;
         }
         if (endpoint != null)
         {
             Marshal.ReleaseComObject(endpoint); endpoint = null;
         }
         if (enumerator != null)
         {
             Marshal.ReleaseComObject(enumerator); enumerator = null;
         }
         isInited = false;
         buffers  = null;
         thread   = null;
         i8Buf    = null; i16Buf = null;
         i32Buf   = null; f32Buf = null;
         f64Buf   = null;
     }
 }
Exemple #24
0
        private static IAudioEndpointVolume GetMasterVolumeObject()
        {
            IAudioEndpointVolume masterVolume = null;

            IMMDeviceEnumerator deviceEnumerator = null;
            IMMDevice           defautOutDevice  = null;

            try
            {
                deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out defautOutDevice);

                Guid   IID_IAudioEndpointVolume = typeof(IAudioEndpointVolume).GUID;
                object o;
                defautOutDevice.Activate(IID_IAudioEndpointVolume, 0, IntPtr.Zero, out o);
                masterVolume = (IAudioEndpointVolume)o;
            }
            finally
            {
                if (defautOutDevice != null)
                {
                    Marshal.ReleaseComObject(defautOutDevice);
                }
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }

            return(masterVolume);
        }
        public static float SetMasterVolume(float newValue)
        {
            // retrieve audio device...

            IMMDeviceEnumerator useenumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice           speakers;
            const int           eRender     = 0;
            const int           eMultimedia = 1;

            //retrieve the actual endpoint
            useenumerator.GetDefaultAudioEndpoint(eRender, ERole.eMultimedia, out speakers);

            object o;

            //retrieve the actual interface instance to retrieve the volume information from.
            speakers.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out o);
            IAudioEndpointVolume aepv = (IAudioEndpointVolume)o;
            float result;
            int   hresult = aepv.GetMasterVolumeLevelScalar(out result);

            aepv.SetMasterVolumeLevelScalar(newValue, new System.Guid());
            Marshal.ReleaseComObject(aepv);
            Marshal.ReleaseComObject(speakers);
            Marshal.ReleaseComObject(useenumerator);
            return(result);
        }
Exemple #26
0
        /// <summary>
        /// Returns a list of the system's enabled audio output devices. Returns null if no enabled audio output devices are present. See also: Player.Audio.DeviceCount and Player.Audio.GetDefaultDevice.
        /// </summary>
        public AudioDevice[] GetDevices()
        {
            AudioDevice[] audioDevices = null;
            _base._lastError = HResult.MF_E_NO_AUDIO_PLAYBACK_DEVICE;

            IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();

            deviceEnumerator.EnumAudioEndpoints(EDataFlow.eRender, (uint)DeviceState.Active, out IMMDeviceCollection deviceCollection);
            Marshal.ReleaseComObject(deviceEnumerator);

            if (deviceCollection != null)
            {
                deviceCollection.GetCount(out uint count);
                if (count > 0)
                {
                    audioDevices = new AudioDevice[count];
                    for (int i = 0; i < count; i++)
                    {
                        audioDevices[i] = new AudioDevice();

                        deviceCollection.Item((uint)i, out IMMDevice device);
                        Player.GetDeviceInfo(device, audioDevices[i]);

                        Marshal.ReleaseComObject(device);
                    }
                    _base._lastError = Player.NO_ERROR;
                }
                Marshal.ReleaseComObject(deviceCollection);
            }
            return(audioDevices);
        }
Exemple #27
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);
        }
Exemple #28
0
 /// <summary>
 /// Call this method to release all com objetcs
 /// </summary>
 public virtual void Dispose()
 {
     if (iAudioEndpoint != null)
     {
         System.Runtime.InteropServices.Marshal.ReleaseComObject(iAudioEndpoint);
         iAudioEndpoint = null;
     }
     if (oEndPoint != null)
     {
         System.Runtime.InteropServices.Marshal.ReleaseComObject(oEndPoint);
         oEndPoint = null;
     }
     if (imd != null)
     {
         System.Runtime.InteropServices.Marshal.ReleaseComObject(imd);
         imd = null;
     }
     if (oDevice != null)
     {
         System.Runtime.InteropServices.Marshal.ReleaseComObject(oDevice);
         oDevice = null;
     }
     if (iMde != null)
     {
         System.Runtime.InteropServices.Marshal.ReleaseComObject(iMde);
         iMde = null;
     }
     if (oEnumerator != null)
     {
         System.Runtime.InteropServices.Marshal.ReleaseComObject(oEnumerator);
         oEnumerator = null;
     }
 }
Exemple #29
0
        private static ISimpleAudioVolume GetVolumeObject(int?pid)
        {
            IMMDeviceEnumerator deviceEnumerator = MMDeviceEnumeratorFactory.CreateInstance();

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

            Guid IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID;

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

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

            ISimpleAudioVolume volumeControl = null;

            for (int i = 0; i < count; i++)
            {
                sessionEnumerator.GetSession(i, out IAudioSessionControl2 ctl);
                ctl.GetProcessId(out int 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);
        }
        public static IAudioEndpointVolume GetMasterVolumeHandler()
        {
            IMMDeviceEnumerator deviceEnumerator = null;
            IMMDevice           speakers         = null;

            try
            {
                deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);

                var audioEndpointVolume = typeof(IAudioEndpointVolume).GUID;
                speakers.Activate(ref audioEndpointVolume, 0, IntPtr.Zero, out object masterVolume);
                return((IAudioEndpointVolume)masterVolume);
            }
            finally
            {
                if (speakers != null)
                {
                    Marshal.ReleaseComObject(speakers);
                }
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }
        }
Exemple #31
0
		/// <summary>
		/// Creates a new MM Device Enumerator
		/// </summary>
		public MMDeviceEnumerator()
		{
			if (Environment.OSVersion.Version.Major < 6)
			{
				throw new NotSupportedException("This functionality is only supported on Windows Vista or newer.");
			}
			_realEnumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
		}
            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);
                }
            }
        /// <summary>

        /// Call this method to release all com objetcs

        /// </summary>

        public virtual void Dispose()
        {

            /*

            if (delMixerChange != null && iAudioEndpoint != null)

            {

            iAudioEndpoint.UnregisterControlChangeNotify(delMixerChange);

            }

            */

            if (iAudioEndpoint != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(iAudioEndpoint);

                iAudioEndpoint = null;

            }

            if (oEndPoint != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(oEndPoint);

                oEndPoint = null;

            }

            if (imd != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(imd);

                imd = null;

            }

            if (oDevice != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(oDevice);

                oDevice = null;

            }

            //System.Runtime.InteropServices.Marshal.ReleaseComObject(pCollection);

            if (iMde != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(iMde);

                iMde = null;

            }

            if (oEnumerator != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(oEnumerator);

                oEnumerator = null;

            }

        }
        //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)");

            }

            */

        }
 /// <summary>
 /// Called to dispose/finalize contained objects.
 /// </summary>
 /// <param name="disposing">True if disposing, false if called from a finalizer.</param>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (realEnumerator != null)
         {
             // although GC would do this for us, we want it done now
             Marshal.ReleaseComObject(realEnumerator);
             realEnumerator = null;
         }
     }
 }
        public virtual void Dispose()
        {
            if (iAudioEndpoint != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(iAudioEndpoint);

                iAudioEndpoint = null;

            }

            if (oEndPoint != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(oEndPoint);

                oEndPoint = null;

            }

            if (imd != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(imd);

                imd = null;

            }

            if (oDevice != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(oDevice);

                oDevice = null;

            }

            if (iMde != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(iMde);

                iMde = null;

            }

            if (oEnumerator != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(oEnumerator);

                oEnumerator = null;

            }
        }
 private MMDeviceEnumerator(IMMDeviceEnumerator inner)
 {
     _inner = inner;
     this.RegisterEndpointNotificationCallback(this);
 }