public override void UninitializeAudio()
 {
     if (null != _audioEndpointVolume)
     {
         _audioEndpointVolume.UnregisterControlChangeNotify(classCallBack);
     }
     if (null != _audioClient)
     {
         _audioClient.Stop();
     }
     if (null != _audioMeter)
     {
         //For wait audio meter thread stop. then release memory
         Thread.Sleep(100);
         Marshal.ReleaseComObject(_audioMeter);
         _audioMeter = null;
     }
     if (null != _audioClient)
     {
         Marshal.ReleaseComObject(_audioClient);
         _audioClient = null;
     }
     if (null != _audioEndpointVolume)
     {
         Marshal.ReleaseComObject(_audioEndpointVolume);
         _audioEndpointVolume = null;
     }
     if (null != waveFormat)
     {
         waveFormat = null;
     }
     base.UninitializeAudio();
 }
Example #2
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();
        }
Example #3
0
 internal AudioMeterInformation(IAudioMeterInformation realInterface)
 {
     _AudioMeterInformation = realInterface;
     Marshal.ThrowExceptionForHR(_AudioMeterInformation.QueryHardwareSupport(out int HardwareSupp));
     _HardwareSupport = (EEndpointHardwareSupport)HardwareSupp;
     _Channels        = new AudioMeterInformationChannels(_AudioMeterInformation);
 }
Example #4
0
        internal void PeakMeter_Close()
        {
            if (pm_HasPeakMeter)
            {
                if (_playing && _mediaPeakLevelChanged != null)
                {
                    _peakLevelArgs._channelCount    = pm_PeakMeterChannelCount;
                    _peakLevelArgs._masterPeakValue = STOP_VALUE;
                    _peakLevelArgs._channelsValues  = pm_PeakMeterValuesStop;
                    _mediaPeakLevelChanged(this, _peakLevelArgs);
                }

                pm_PeakMeterChannelCount = 0;
                pm_PeakMeterMasterValue  = 0;
                pm_HasPeakMeter          = false;

                try
                {
                    Marshal.ReleaseComObject(pm_PeakMeterInfo);
                    pm_PeakMeterInfo = null;

                    StopSystemDevicesChangedHandlerCheck();
                }
                catch { /* ignore */ }
            }
        }
        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);
        }
Example #6
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);
            }
        }
 internal AudioMeterInformation(IAudioMeterInformation realInterface)
 {
     audioMeterInformation = realInterface;
     Marshal.ThrowExceptionForHR(audioMeterInformation.QueryHardwareSupport(out var hardwareSupp));
     HardwareSupport = (EEndpointHardwareSupport)hardwareSupp;
     PeakValues      = new AudioMeterInformationChannels(audioMeterInformation);
 }
Example #8
0
        public static float[] ReadPeakValues(IAudioMeterInformation meter)
        {
            var ret = new float[2];

            try
            {
                uint chanCount = meter.GetMeteringChannelCount();
                if (chanCount > 0)
                {
                    var arrayPtr = Marshal.AllocHGlobal((int)chanCount * 4); // 4 bytes in float
                    if (meter.GetChannelsPeakValues(chanCount, arrayPtr) == HRESULT.S_OK)
                    {
                        var values = new float[chanCount];
                        Marshal.Copy(arrayPtr, values, 0, (int)chanCount);

                        if (chanCount == 1)
                        {
                            ret[0] = values[0];
                            ret[1] = values[0];
                        }
                        else
                        {
                            ret[0] = values[0];
                            ret[1] = values[1];
                        }
                    }
                }
            }
            catch (Exception ex) when(ex.Is(HRESULT.AUDCLNT_E_DEVICE_INVALIDATED))
            {
                // Expected in some cases.
            }
            return(ret);
        }
        /// <summary>
        /// The Initialize Audio Client
        /// </summary>
        /// <param name="audioFlow"></param>
        /// <param name="_deviceEnumerator"></param>
        private void InitializeAudioClient()
        {
            //Get Audio Client from device
            COMResult 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;
            //Get Audio End Point
            result = _audioDevice.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out obj);
            _audioEndpointVolume = (IAudioEndpointVolume)obj;
            _audioEndpointVolume.RegisterControlChangeNotify(classCallBack);
            //Initialize Audio Client.
            _sessionGuid = new Guid();
            result       = _audioClient.GetMixFormat(out waveFormat);
            AudioClientStreamFlags streamFlag = AudioClientStreamFlags.None;

            if (_audioDataFlow == AudioDataFlow.eRender)
            {
                streamFlag = AudioClientStreamFlags.Loopback;
            }
            result = _audioClient.Initialize(AudioClientMode.Shared, streamFlag, 10000000, 0, waveFormat, ref _sessionGuid);
            result = _audioClient.Start();
            //Change wave format here
            SetupWaveFormat(waveFormat);

            result = _audioEndpointVolume.GetChannelCount(out _channelCount);
        }
Example #10
0
        // ******************************** Audio Devices - Audio Input Peak Meter - Open / Close / GetValues

        #region  Audio Devices - Audio Input Peak Meter - Open / Close / GetValues

        internal bool InputMeter_Open(AudioInputDevice device, bool change)
        {
            // tested for null at event subscription

            if (!pm_HasInputMeter || change)
            {
                IMMDeviceEnumerator deviceEnumerator = null;
                IMMDevice           levelDevice      = null;

                if (pm_HasInputMeter)
                {
                    InputMeter_Close();
                }

                try
                {
                    deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
                    deviceEnumerator.GetDevice(device._id, out levelDevice);

                    if (levelDevice != null)
                    {
                        levelDevice.Activate(ref IID_IAudioMeterInformation, 3, IntPtr.Zero, out object levelDeviceInfo);
                        pm_InputMeterInfo = (IAudioMeterInformation)levelDeviceInfo;

                        pm_InputMeterInfo.GetMeteringChannelCount(out pm_InputMeterChannelCount);
                        if (pm_InputMeterChannelCount > MAX_AUDIO_CHANNELS)
                        {
                            pm_InputMeterChannelCount = MAX_AUDIO_CHANNELS;
                        }

                        if (pm_InputMeterValues == null)
                        {
                            pm_InputMeterValues     = new float[MAX_AUDIO_CHANNELS];
                            pm_InputMeterValuesStop = new float[MAX_AUDIO_CHANNELS];
                            for (int i = 0; i < MAX_AUDIO_CHANNELS; i++)
                            {
                                pm_InputMeterValuesStop[i] = STOP_VALUE;
                            }
                        }
                        pm_HasInputMeter = true;

                        //StartSystemDevicesChangedHandlerCheck();
                    }
                }
                catch
                { /* ignore */
                }

                if (levelDevice != null)
                {
                    Marshal.ReleaseComObject(levelDevice);
                }
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }
            return(pm_HasInputMeter);
        }
Example #11
0
 private void Dispose(bool disposing)
 {
     if (disposing)
     {
         _audioMeterInformation = null;
         _channels = null;
     }
 }
Example #12
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());
        }
Example #13
0
        internal AudioMeterInformation(IAudioMeterInformation realInterface)
        {
            this.audioMeterInformation = realInterface;
            int num;

            Marshal.ThrowExceptionForHR(this.audioMeterInformation.QueryHardwareSupport(out num));
            this.hardwareSupport = (EEndpointHardwareSupport)num;
            this.channels        = new AudioMeterInformationChannels(this.audioMeterInformation);
        }
Example #14
0
		internal AudioMeterInformation(IAudioMeterInformation realInterface)
		{
			int HardwareSupp;

			_AudioMeterInformation = realInterface;
			Marshal.ThrowExceptionForHR(_AudioMeterInformation.QueryHardwareSupport(out HardwareSupp));
			_HardwareSupport = (EEndpointHardwareSupport) HardwareSupp;
			_Channels = new AudioMeterInformationChannels(_AudioMeterInformation);
		}
        internal AudioMeterInformation(IAudioMeterInformation realInterface)
        {
            ComThread.Assert();
            uint hardwareSupp;

            _audioMeterInformation = realInterface;
            Marshal.ThrowExceptionForHR(_audioMeterInformation.QueryHardwareSupport(out hardwareSupp));
            _hardwareSupport = (EndpointHardwareSupport)hardwareSupp;
            _channels = new AudioMeterInformationChannels(_audioMeterInformation);
        }
Example #16
0
        internal AudioMeterInformation(IAudioMeterInformation realInterface)
        {
            ComThread.Assert();
            uint hardwareSupp;

            _audioMeterInformation = realInterface;
            Marshal.ThrowExceptionForHR(_audioMeterInformation.QueryHardwareSupport(out hardwareSupp));
            _hardwareSupport = (EndpointHardwareSupport)hardwareSupp;
            _channels        = new AudioMeterInformationChannels(_audioMeterInformation);
        }
        public static float GetPeakVolume(ISimpleAudioVolume v)
        {
            if (v == null)
            {
                return(0f);
            }

            IAudioMeterInformation meter = (IAudioMeterInformation)v;

            meter.GetPeakValue(out float peak);
            return(peak * 100);
        }
Example #18
0
        public static float?GetApplicationPeak(int pid)
        {
            IAudioMeterInformation meter = VolumeMixer.GetCoreAudioObject <IAudioMeterInformation>(pid);

            if (meter == null)
            {
                return(null);
            }

            float peak;

            meter.GetPeakValue(out peak);
            return(peak);
        }
Example #19
0
        internal AudioSessionControl(IAudioSessionControl2 realAudioSessionControl)
        {
            IAudioMeterInformation realInterface    = realAudioSessionControl as IAudioMeterInformation;
            ISimpleAudioVolume     realSimpleVolume = realAudioSessionControl as ISimpleAudioVolume;

            if (realInterface != null)
            {
                this._AudioMeterInformation = new CoreAudioApi.AudioMeterInformation(realInterface);
            }
            if (realSimpleVolume != null)
            {
                this._SimpleAudioVolume = new CoreAudioApi.SimpleAudioVolume(realSimpleVolume);
            }
            this._AudioSessionControl = realAudioSessionControl;
        }
Example #20
0
        // FAB
        // int nProcessID = Process.GetCurrentProcess().Id;
        public static float?GetApplicationMasterPeakVolume(int pid)
        {
            IAudioMeterInformation masterpeakvol = GetMasterPeakVolume(pid);

            if (masterpeakvol == null)
            {
                return(null);
            }

            float peak;

            masterpeakvol.GetPeakValue(out peak);
            Marshal.ReleaseComObject(masterpeakvol);
            return(peak * 100);
        }
Example #21
0
        internal AudioSessionControl(IAudioSessionControl2 realAudioSessionControl)
        {
            IAudioMeterInformation _meters = realAudioSessionControl as IAudioMeterInformation;
            ISimpleAudioVolume     _volume = realAudioSessionControl as ISimpleAudioVolume;

            if (_meters != null)
            {
                _AudioMeterInformation = new AxVolume.AudioMeterInformation(_meters);
            }
            if (_volume != null)
            {
                _SimpleAudioVolume = new SimpleAudioVolume(_volume);
            }
            _AudioSessionControl = realAudioSessionControl;
        }
Example #22
0
        public AudioSessionControl(IAudioSessionControl audioSessionControl)
        {
            this.audioSessionControlInterface  = audioSessionControl;
            this.audioSessionControlInterface2 = (audioSessionControl as IAudioSessionControl2);
            IAudioMeterInformation audioMeterInformation = this.audioSessionControlInterface as IAudioMeterInformation;
            ISimpleAudioVolume     simpleAudioVolume     = this.audioSessionControlInterface as ISimpleAudioVolume;

            if (audioMeterInformation != null)
            {
                this.audioMeterInformation = new AudioMeterInformation(audioMeterInformation);
            }
            if (simpleAudioVolume != null)
            {
                this.simpleAudioVolume = new SimpleAudioVolume(simpleAudioVolume);
            }
        }
        internal AudioSessionControl(IAudioSessionControl realAudioSessionControl)
        {
            IAudioMeterInformation _meters = realAudioSessionControl as IAudioMeterInformation;
            ISimpleAudioVolume     _volume = realAudioSessionControl as ISimpleAudioVolume;

            if (_meters != null)
            {
                _AudioMeterInformation = new CoreAudio.AudioMeterInformation(_meters);
            }
            if (_volume != null)
            {
                _SimpleAudioVolume = new SimpleAudioVolume(_volume);
            }
            _AudioSessionControl = realAudioSessionControl;

            //_AudioSessionEvents = new AudioSessionEvents(this);
            Marshal.ThrowExceptionForHR(_AudioSessionControl.RegisterAudioSessionNotification(_AudioSessionEvents));
        }
Example #24
0
        public AudioDevice(IMMDevice device)
        {
            _device     = device;
            _dispatcher = App.Current.Dispatcher;
            _id         = device.GetId();

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

            _deviceVolume = device.Activate <IAudioEndpointVolume>();

            _deviceVolume.RegisterControlChangeNotify(this);
            _meter    = device.Activate <IAudioMeterInformation>();
            _sessions = new AudioDeviceSessionCollection(this, _device);

            _deviceVolume.GetMasterVolumeLevelScalar(out _volume);
            _isMuted = _deviceVolume.GetMute() != 0;

            ReadDisplayName();
        }
Example #25
0
        internal AudioSessionControl2(IAudioSessionControl2 realAudioSessionControl2)
        {
            _AudioSessionControl2 = realAudioSessionControl2;

            IAudioMeterInformation _meters = _AudioSessionControl2 as IAudioMeterInformation;

            if (_meters != null)
            {
                _AudioMeterInformation = new CoreAudio.AudioMeterInformation(_meters);
            }

            ISimpleAudioVolume _volume1 = _AudioSessionControl2 as ISimpleAudioVolume;

            if (_volume1 != null)
            {
                _SimpleAudioVolume = new SimpleAudioVolume(_volume1);
            }

            //IAudioVolumeLevel _volume2 = _AudioSessionControl2 as IAudioVolumeLevel;
            //if (_volume2 != null) _AudioVolumeLevel = new AudioVolumeLevel(_volume2);

            _AudioSessionEvents = new AudioSessionEvents(this);
            Marshal.ThrowExceptionForHR(_AudioSessionControl2.RegisterAudioSessionNotification(_AudioSessionEvents));
        }
Example #26
0
        // ******************************** Player Peak Meter - Open / Close / GetValues

        #region Player Peak Meter - Open / Close / GetValues

        internal bool PeakMeter_Open(AudioDevice device, bool change)
        {
            if (!pm_HasPeakMeter || change)
            {
                IMMDeviceEnumerator deviceEnumerator = null;
                IMMDevice           levelDevice      = null;
                object levelDeviceInfo;

                if (pm_HasPeakMeter)
                {
                    PeakMeter_Close();
                }

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

                    if (levelDevice != null)
                    {
                        levelDevice.Activate(ref IID_IAudioMeterInformation, 3, IntPtr.Zero, out levelDeviceInfo);
                        pm_PeakMeterInfo = (IAudioMeterInformation)levelDeviceInfo;

                        pm_PeakMeterInfo.GetMeteringChannelCount(out pm_PeakMeterChannelCount);
                        if (pm_PeakMeterChannelCount > MAX_AUDIO_CHANNELS)
                        {
                            pm_PeakMeterChannelCount = MAX_AUDIO_CHANNELS;
                        }

                        if (pm_PeakMeterValues == null)
                        {
                            pm_PeakMeterValues     = new float[MAX_AUDIO_CHANNELS];
                            pm_PeakMeterValuesStop = new float[MAX_AUDIO_CHANNELS];
                            for (int i = 0; i < MAX_AUDIO_CHANNELS; i++)
                            {
                                pm_PeakMeterValuesStop[i] = STOP_VALUE;
                            }
                        }
                        pm_HasPeakMeter = true;

                        StartSystemDevicesChangedHandlerCheck();
                    }
                }
                catch
                { /* ignore */
                }

                if (levelDevice != null)
                {
                    Marshal.ReleaseComObject(levelDevice);
                }
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }
            return(pm_HasPeakMeter);
        }
 public void Dispose()
 {
     _AudioMeterInformation = null;
 }
Example #28
0
        // Fab: get the master volume peak
        // https://github.com/maindefine/volumecontrol/blob/master/C%23/CoreAudioApi/AudioMeterInformation.cs
        private static IAudioMeterInformation GetMasterPeakVolume(int pid)
        {
            IMMDeviceEnumerator     deviceEnumerator  = null;
            IAudioSessionEnumerator sessionEnumerator = null;
            IAudioSessionManager2   mgr = null;
            IMMDevice speakers          = null;

            IAudioSessionControl2 ctl = null;

            try
            {
                // get the speakers (1st render + multimedia) device
                deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
                deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);

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

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

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

                // search for an audio session with the required process-id
                //ISimpleAudioVolume volumeControl = null;
                IAudioMeterInformation mastervol = null;


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

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

                        if (cpid == pid)
                        {
                            //volumeControl = ctl as ISimpleAudioVolume;
                            mastervol = ctl as IAudioMeterInformation;

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


                //return volumeControl;
                return(mastervol);
            }
            finally
            {
                if (sessionEnumerator != null)
                {
                    Marshal.ReleaseComObject(sessionEnumerator);
                }
                if (mgr != null)
                {
                    Marshal.ReleaseComObject(mgr);
                }
                if (speakers != null)
                {
                    Marshal.ReleaseComObject(speakers);
                }
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }

                //if (ctl != null) Marshal.ReleaseComObject(ctl);
            }
        }
 internal AudioMeterInformationChannels(IAudioMeterInformation parent)
 {
     _AudioMeterInformation = parent;
 }
 internal AudioMeterInformation(IAudioMeterInformation realInterface)
 {
     Channels = new AudioMeterInformationChannels(realInterface);
 }
 internal AudioMeterInformation(IAudioMeterInformation realInterface)
 {
     _AudioMeterInformation = realInterface;
     Channels = new AudioMeterInformationChannels(_AudioMeterInformation);
 }
 internal AudioMeterInformationChannels(IAudioMeterInformation parent)
 {
     _AudioMeterInformation = parent;
 }
 internal AudioMeterInformation(IAudioMeterInformation realInterface)
 {
     _AudioMeterInformation = realInterface;
     Channels = new AudioMeterInformationChannels(_AudioMeterInformation);
 }
Example #34
0
        //считывает текущее значение уровней звука и обновляет UI
        public void UpdateVisualizer()
        {
            if (speakers == null)
            {
                return;
            }

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

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

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

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

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

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

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

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

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

                if (ctl != null)
                {
                    Marshal.ReleaseComObject(ctl); ctl = null;
                }
                if (ctl2 != null)
                {
                    Marshal.ReleaseComObject(ctl2); ctl2 = null;
                }
                if (meter != null)
                {
                    Marshal.ReleaseComObject(meter); meter = null;
                }
            }
        }
Example #35
0
 internal AudioMeterInformation(IAudioMeterInformation realInterface)
 {
     Channels = new AudioMeterInformationChannels(realInterface);
 }
 private void Dispose(bool disposing)
 {
     if (disposing)
     {
         _audioMeterInformation = null;
         _channels = null;
     }
 }