Ejemplo n.º 1
1
 public AEDev()
 {
   IMMDevice _Device = null;
   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(String.Format("audio device is not active ({0})", 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));
 }
Ejemplo n.º 2
0
        private AudioClient GetAudioClient()
        {
            object result;

            Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioClient, ClsCtx.ALL, IntPtr.Zero, out result));
            return(new AudioClient(result as IAudioClient));
        }
Ejemplo n.º 3
0
        private AudioClient GetAudioClient()
        {
            object result;

            deviceInterface.Activate(typeof(IAudioClient).GUID, ClsCtx.ALL, IntPtr.Zero, out result);
            return(new AudioClient(result as IAudioClient));
        }
Ejemplo n.º 4
0
        private AudioSessionManager GetAudioSessionManager()
        {
            object result;

            Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioSessionManager, CLSCTX.ALL, IntPtr.Zero, out result));
            return(new AudioSessionManager((IAudioSessionManager2)result));
        }
Ejemplo n.º 5
0
        //private AudioClient GetAudioClient()
        //{
        //    Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioClient, ClsCtx.ALL, IntPtr.Zero, out var result));
        //    return new AudioClient(result as IAudioClient);
        //}

        private void GetAudioMeterInformation()
        {
            object result;

            Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioMeterInformation, ClsCtx.All, IntPtr.Zero, out result));
            _audioMeterInformation = new AudioMeterInformation(result as IAudioMeterInformation);
        }
Ejemplo n.º 6
0
        public AudioDevice(IAudioDeviceManager deviceManager, IMMDevice device, Dispatcher foregroundDispatcher)
        {
            _device        = device;
            _deviceManager = new WeakReference <IAudioDeviceManager>(deviceManager);
            _dispatcher    = foregroundDispatcher;
            _id            = device.GetId();

            Trace.WriteLine($"AudioDevice Create {_id}");

            if (_device.GetState() == DeviceState.ACTIVE)
            {
                _deviceVolume = device.Activate <IAudioEndpointVolume>();
                _deviceVolume.RegisterControlChangeNotify(this);
                _deviceVolume.GetMasterVolumeLevelScalar(out _volume);
                _isMuted       = _deviceVolume.GetMute() != 0;
                _isRegistered  = true;
                _meter         = device.Activate <IAudioMeterInformation>();
                _channels      = new AudioDeviceChannelCollection(_deviceVolume, _dispatcher);
                _sessions      = new AudioDeviceSessionCollection(this, _device, _dispatcher);
                _sessionFilter = new FilteredCollectionChain <IAudioDeviceSession>(_sessions.Sessions, _dispatcher);
                Groups         = _sessionFilter.Items;
            }
            else
            {
                Groups = new ObservableCollection <IAudioDeviceSession>();
            }

            ReadProperties();
        }
Ejemplo n.º 7
0
        private void GetAudioMeterInformation()
        {
            object result;

            Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioMeterInformation, CLSCTX.ALL, IntPtr.Zero, out result));
            _AudioMeterInformation = new AudioMeterInformation(result as IAudioMeterInformation);
        }
Ejemplo n.º 8
0
        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);
        }
Ejemplo n.º 9
0
        private void GetAudioSessionManager()
        {
            object result;

            Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioSessionManager, CLSCTX.ALL, IntPtr.Zero, out result));
            _AudioSessionManager = new AudioSessionManager(result as IAudioSessionManager2);
        }
Ejemplo n.º 10
0
 // Release object after usage using "Marshal.ReleaseComObject(VAR);
 public IAudioSessionManager2 GetDeviceManager()
 {
     object o;
     Guid guid = typeof(IAudioSessionManager2).GUID;
     if (DeviceToUse.Activate(ref guid, (int)CLSCTX.CLSCTX_ALL, IntPtr.Zero, out o) != 0 || o == null)
     {
         return null;
     }
     return o as IAudioSessionManager2;
 }
Ejemplo n.º 11
0
        public VolumeService()
        {
            // get the speakers (1st render + multimedia) device
            var deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());

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

            object o;
            //retrieve the actual interface instance to retrieve the volume information from.
            var guid = typeof(IAudioEndpointVolume).GUID;

            _speakers.Activate(ref guid, 0, IntPtr.Zero, out o);
            _aepv = (IAudioEndpointVolume)o;
            Marshal.ReleaseComObject(deviceEnumerator);
        }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
0
        public AEDev()
        {
            IMMDevice _Device = null;

            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(String.Format("audio device is not active ({0})", 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));
        }
Ejemplo n.º 14
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);
        }
Ejemplo n.º 15
0
        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
                }
            }
        }
Ejemplo n.º 16
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);
        }
Ejemplo n.º 17
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
 }
Ejemplo n.º 18
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
        }
Ejemplo n.º 19
0
        private static IAudioEndpointVolume GetMasterMicVolumeObject()
        {
            IMMDeviceEnumerator deviceEnumerator = null;
            IMMDevice           mic = null;

            try
            {
                deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eCommunications, out mic);

                Guid   IID_IAudioEndpointVolume = typeof(IAudioEndpointVolume).GUID;
                object o;
                mic.Activate(ref IID_IAudioEndpointVolume, 0, IntPtr.Zero, out o);
                IAudioEndpointVolume masterVol = (IAudioEndpointVolume)o;
                return(masterVol);
            }
            finally
            {
                if (mic != null)
                {
                    Marshal.ReleaseComObject(mic);
                }
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }
        }
Ejemplo n.º 20
0
        private void GetAudioEndpointVolume()
        {
            object result;

            Marshal.ThrowExceptionForHR(_device.Activate(IID_IAudioEndpointVolume, ClsCtx.All, IntPtr.Zero, out result));
            _audioEndpointVolume = new AudioEndpointVolume(result as IAudioEndpointVolume);
        }
Ejemplo n.º 21
0
        private void GetAudioEndpointVolume()
        {
            object result;

            Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioEndpointVolume, CLSCTX.ALL, IntPtr.Zero, out result));
            _AudioEndpointVolume = new AudioEndpointVolume(result as IAudioEndpointVolume);
        }
Ejemplo n.º 22
0
        public static void listDeviceProperties(IMMDevice dev, DEVICE_SUMMARY defaultDevice)
        {
            IPropertyStore propertyStore;

            dev.OpenPropertyStore(0 /*STGM_READ*/, out propertyStore);
            PROPVARIANT property;  propertyStore.GetValue(ref PropertyKey.PKEY_Device_EnumeratorName, out property);

            System.Console.WriteLine(" EnumeratorName: " + (string)property.Value);
            propertyStore.GetValue(ref PropertyKey.PKEY_Device_FriendlyName, out property);
            System.Console.WriteLine(" FriendlyName: " + (string)property.Value);
            if (!defaultDevice.Equals(null) && defaultDevice.FriendlyName == (string)property.Value)
            {
                System.Console.WriteLine(" **Default: True**");
            }
            Marshal.ReleaseComObject(propertyStore);

            IAudioEndpointVolume epv = null;
            var epvid = typeof(IAudioEndpointVolume).GUID;

            Marshal.ThrowExceptionForHR(dev.Activate(ref epvid, /*CLSCTX_ALL*/ 23, 0, out epv));

            bool mute;  epv.GetMute(out mute);  if (mute)
            {
                System.Console.WriteLine(" **GetMute: " + mute + "**");
            }
            float vol;  epv.GetMasterVolumeLevelScalar(out vol);  System.Console.WriteLine(" GetMasterVolumeLevelScalar: " + vol);
        }
Ejemplo n.º 23
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);
                }
            }
        }
Ejemplo n.º 24
0
        private void LoadAudioMeterInformation(IMMDevice device)
        {
            //This should be all on the COM thread to avoid any
            //weird lookups on the result COM object not on an STA Thread
            ComThread.Assert();

            object    result = null;
            Exception ex;

            //Need to catch here, as there is a chance that unauthorized is thrown.
            //It's not an HR exception, but bubbles up through the .net call stack
            try
            {
                var clsGuid = new Guid(ComIIds.AUDIO_METER_INFORMATION_IID);
                ex = Marshal.GetExceptionForHR(device.Activate(ref clsGuid, ClsCtx.Inproc, IntPtr.Zero, out result));
            }
            catch (Exception e)
            {
                ex = e;
            }

            if (ex != null)
            {
                ClearAudioMeterInformation();
                return;
            }

            _audioMeterInformation = new AudioMeterInformation(result as IAudioMeterInformation);
        }
Ejemplo n.º 25
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);
            }
        }
        public AudioDeviceSessionCollection(IAudioDevice parent, IMMDevice device)
        {
            Trace.WriteLine($"AudioDeviceSessionCollection Create dev={device.GetId()}");

            _parent     = new WeakReference <IAudioDevice>(parent);
            _dispatcher = App.Current.Dispatcher;

            Task.Factory.StartNew(() =>
            {
                try
                {
                    _sessionManager = device.Activate <IAudioSessionManager2>();
                    _sessionManager.RegisterSessionNotification(this);
                    var enumerator = _sessionManager.GetSessionEnumerator();
                    int count      = enumerator.GetCount();
                    for (int i = 0; i < count; i++)
                    {
                        CreateAndAddSession(enumerator.GetSession(i));
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError($"{ex}");
                }
            });
        }
Ejemplo n.º 27
0
        // ******************************** Player Peak Meter - Audio Device - Master Volume / ChannelCount

        #region Player Peak Meter - Audio Device - Master Volume / ChannelCount

        internal static float AudioDevice_MasterVolume(AudioDevice device, float volume, bool set)
        {
            lock (pm_PeakMeterLock2)
            {
                IMMDeviceEnumerator deviceEnumerator = null;
                IMMDevice           levelDevice      = null;
                object levelDeviceInfo = null;
                float  getVolume       = 0;

                try
                {
                    deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
                    if (device == null)
                    {
                        deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out levelDevice);
                    }
                    else
                    {
                        deviceEnumerator.GetDevice(device._id, out levelDevice);
                    }

                    levelDevice.Activate(ref IID_IAudioEndpointVolume, 3, IntPtr.Zero, out levelDeviceInfo);
                    if (set)
                    {
                        // TODO set out of range?
                        if (volume <= 0)
                        {
                            volume = 0;
                        }
                        else if (volume > 1)
                        {
                            volume = 1;
                        }
                        ((IAudioEndpointVolume)levelDeviceInfo).SetMasterVolumeLevelScalar(volume, Guid.Empty);
                        getVolume = volume;
                    }
                    else
                    {
                        ((IAudioEndpointVolume)levelDeviceInfo).GetMasterVolumeLevelScalar(out getVolume);
                    }
                }
                catch { getVolume = -1; }

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

                return(getVolume);
            }
        }
Ejemplo n.º 28
0
        // gets global volume endpoint
        private static void GetAudioEndpointVolume(IMMDevice speakers, out IAudioEndpointVolume aev)
        {
            Guid   IID_IAudioEndpointVolume = typeof(IAudioEndpointVolume).GUID;
            object o;

            speakers.Activate(ref IID_IAudioEndpointVolume, 0, IntPtr.Zero, out o);
            aev = (IAudioEndpointVolume)o;
        }
Ejemplo n.º 29
0
        // activate the session manager. we need the enumerator
        private static void GetSessionManager(IMMDevice speakers, out IAudioSessionManager2 mgr)
        {
            Guid   IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID;
            object o;

            speakers.Activate(ref IID_IAudioSessionManager2, 0, IntPtr.Zero, out o);
            mgr = (IAudioSessionManager2)o;
        }
Ejemplo n.º 30
0
        private static IAudioSessionManager2 GetOutputDeviceSessionManager(IMMDevice outputDevice)
        {
            Guid   IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID;
            object o;

            outputDevice.Activate(ref IID_IAudioSessionManager2, 0, IntPtr.Zero, out o);
            return((IAudioSessionManager2)o);
        }
Ejemplo n.º 31
0
        public static float getPeakValue()
        {
            IMMDeviceEnumerator    enumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
            IMMDevice              speakers   = enumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
            IAudioMeterInformation meter      = (IAudioMeterInformation)speakers.Activate(typeof(IAudioMeterInformation).GUID, 0, IntPtr.Zero);

            return(meter.GetPeakValue());
        }
        private void LoadAudioEndpointVolume(IMMDevice device)
        {
            //Don't even bother looking up volume for disconnected devices
            if (!State.HasFlag(DeviceState.Active))
            {
                ClearAudioEndpointVolume();
                return;
            }

            //This should be all on the COM thread to avoid any
            //weird lookups on the result COM object not on an STA Thread
            ComThread.Assert();

            object result = null;
            Exception ex;
            //Need to catch here, as there is a chance that unauthorized is thrown.
            //It's not an HR exception, but bubbles up through the .net call stack
            try
            {
                var clsGuid = new Guid(ComIIds.AUDIO_ENDPOINT_VOLUME_IID);
                ex = Marshal.GetExceptionForHR(device.Activate(ref clsGuid, ClsCtx.Inproc, IntPtr.Zero, out result));
            }
            catch (Exception e)
            {
                ex = e;
            }

            if (ex != null)
            {
                ClearAudioEndpointVolume();
                return;
            }

            _audioEndpointVolume = new AudioEndpointVolume(result as IAudioEndpointVolume);
        }
Ejemplo n.º 33
0
 internal AEDev()
 {
   IMMDevice _Device = null;
   Marshal.ThrowExceptionForHR(((IMMDeviceEnumerator)_realEnumerator).GetDefaultAudioEndpoint(0, 1, out _Device));
   _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));
 }
Ejemplo n.º 34
0
        //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)");

            }

            */

        }
        private void LoadAudioMeterInformation(IMMDevice device)
        {
            //This should be all on the COM thread to avoid any
            //weird lookups on the result COM object not on an STA Thread
            ComThread.Assert();

            object result = null;
            Exception ex;
            //Need to catch here, as there is a chance that unauthorized is thrown.
            //It's not an HR exception, but bubbles up through the .net call stack
            try
            {
                var clsGuid = new Guid(ComIIds.AUDIO_METER_INFORMATION_IID);
                ex = Marshal.GetExceptionForHR(device.Activate(ref clsGuid, ClsCtx.Inproc, IntPtr.Zero, out result));
            }
            catch (Exception e)
            {
                ex = e;
            }

            if (ex != null)
            {
                ClearAudioMeterInformation();
                return;
            }

            _audioMeterInformation = new AudioMeterInformation(result as IAudioMeterInformation);
        }