Ejemplo n.º 1
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);
            }
        }
        private float GetPeakValue()
        {
            float result;

            Marshal.ThrowExceptionForHR(_AudioMeterInformation.GetPeakValue(out result));
            return(result);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// The "Visualiser" pattern implementation for the timer, which will result in a
        /// moving visualisation of the data coming in from _audioMeter, where the most right column is
        /// the latest data coming in and all the other keys hold patterns from previous data, oldest
        /// being the most left column
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void VisualisePattern(object source, ElapsedEventArgs e)
        {
            // We get the initial volume level from the COM interface
            float volumeLevel;

            _audioMeter.GetPeakValue(out volumeLevel);

            // We remap the original range to fit to the keyboards rows(that being five rows)W
            float remappedValue = volumeLevel.RemapNumberToNewRange(0, 1, 0, Constants.MaxRows);

            // Then we multiply it by our multiplier, and clamp it to make sure it doesn't exceed the keyboards range
            // We also make sure the number is alrady a whole number, to make casting to an int easier
            remappedValue *= _multiplier;
            float clampedRemappedValue = (float)Math.Ceiling(remappedValue.Clamp(0, Constants.MaxRows));

            // We then reverse the range to fit on the keyboard and cast it to an integer
            int reversedIntegerValue = (int)clampedRemappedValue.RemapNumberToNewRange(0, Constants.MaxRows, Constants.MaxRows, 0);

            for (int c = 0; c < Constants.MaxColumns; c++)
            {
                // Reversed for loop to make sure the keys are lit from bottom to top
                for (int r = (Constants.MaxRows - 1); r > -1; r--)
                {
                    // If this is not a key on the most right column, we copy the value from its neighbour on the right
                    if (c + 1 < Constants.MaxColumns)
                    {
                        Chroma.Instance.Keyboard[r, c] = Chroma.Instance.Keyboard[r, c + 1];
                    }
                    // If this is the most right column, and this row is still within the limit of the data we retreived from _audioMeter,
                    // we light up this key using one of 3 methods, the static color is set on initialisation of the color variable
                    else
                    {
                        if (r >= reversedIntegerValue)
                        {
                            ColoreColor color;
                            switch (_currentMode)
                            {
                            case VisualiserMode.Ramp:
                                color = _colorPicker.RampColor(r);
                                break;

                            case VisualiserMode.Random:
                                color = _colorPicker.RandomColor();
                                break;

                            default:
                                color = defaultColor;
                                break;
                            }
                            Chroma.Instance.Keyboard[r, c] = color;
                        }
                        else
                        {
                            Chroma.Instance.Keyboard[r, c] = ColoreColor.Black;
                        }
                    }
                }
            }
        }
Ejemplo n.º 4
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());
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
0
 // TODO - write directly to _peakLevelArgs?
 private void PeakMeter_GetValues()
 {
     if (pm_HasPeakMeter)
     {
         GCHandle values = GCHandle.Alloc(pm_PeakMeterValues, GCHandleType.Pinned);
         //pm_PeakMeterInfo.GetMeteringChannelCount(out pm_PeakMeterChannelCount);
         pm_PeakMeterInfo.GetChannelsPeakValues(pm_PeakMeterChannelCount, values.AddrOfPinnedObject());
         pm_PeakMeterInfo.GetPeakValue(out pm_PeakMeterMasterValue);
         values.Free();
     }
     else
     {
         for (int i = 0; i < MAX_AUDIO_CHANNELS; i++)
         {
             pm_PeakMeterValues[i] = STOP_VALUE;
         }
     }
 }
Ejemplo n.º 8
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;
                }
            }
        }