Example #1
0
 // Returns the current meter.PeakValue;
 public static double PeakValue(MMDevice device)
 {
     using (var meter = AudioMeterInformation.FromDevice(device))
     {
         return(meter.PeakValue);
     }
 }
        private void UpdatePeakVolume(double deltaTime)
        {
            if (this.IsEnabled == false)
            {
                // To avoid null object exception on _enumerator use after plugin is disabled.
                return;
            }

            if (_playbackDevice == null)
            {
                // To avoid null object exception on device change
                return;
            }

            // Update Main Voulume Peak
            lock (_audioEventLock) // To avoid query an Device/EndPoint that is not the current anymore o has more or less channels
            {
                using (var meter = AudioMeterInformation.FromDevice(_playbackDevice))
                {
                    float _peakVolumeNormalized = meter.PeakValue;
                    DataModel.PeakVolumeNormalized = _peakVolumeNormalized;
                    DataModel.PeakVolume           = _peakVolumeNormalized * 100f;

                    //Update Channels Peak
                    var channelsVolumeNormalized = meter.GetChannelsPeakValues();
                    for (int i = 0; i < DataModel.Channels.DynamicChildren.Count; i++)
                    {
                        var channelDataModel = DataModel.Channels.GetDynamicChild <ChannelDataModel>(string.Format("Channel {0}", i));
                        channelDataModel.Value.PeakVolumeNormalized = Math.Max(channelsVolumeNormalized[i], 0);
                        channelDataModel.Value.PeakVolume           = Math.Max(channelsVolumeNormalized[i] * 100f, 0);
                    }
                }
            }
        }
Example #3
0
        public WindowsAudio()
        {
            var device = new MMDeviceEnumerator().GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);

            _volume = AudioEndpointVolume.FromDevice(device);
            _meter  = AudioMeterInformation.FromDevice(device);
        }
Example #4
0
        private void GetCapture(bool isController, string deviceId = null)
        {
            if (!isController)
            {
                if (_soundCapture != null)
                {
                    _soundCapture?.Stop();
                    _soundCapture?.Dispose();
                }
                using (MMDeviceEnumerator enumerator = new MMDeviceEnumerator())
                {
                    //using (MMDevice device = enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Communications))
                    //{
                    MMDevice device;
                    if (deviceId != null)
                    {
                        device = enumerator.GetDevice(deviceId);
                    }
                    else
                    {
                        device = enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, _currentCaptureRole);
                    }

                    _meter        = AudioMeterInformation.FromDevice(device);
                    _soundCapture = new WasapiCapture(true, AudioClientShareMode.Shared, 250)
                    {
                        Device = device
                    };
                    _soundCapture.Initialize();
                    _soundCapture.Start();
                    //}
                }
            }
        }
Example #5
0
 // Checks if any audio is playing at all
 public bool IsAudioPlaying()
 {
     using (var meter = AudioMeterInformation.FromDevice(this.device))
     {
         return(meter.PeakValue > 0);
     }
 }
Example #6
0
        private void TripTimer(Object source, System.Timers.ElapsedEventArgs e)
        {
            Thread.CurrentThread.IsBackground = true;
            AudioMeterInformation theInfo;
            float peakValue;

            if (inputDevice != null)
            {
                theInfo   = AudioMeterInformation.FromDevice(inputDevice);
                peakValue = theInfo.GetPeakValue();
                inputProgress.Dispatcher.InvokeAsync((Action)(() =>
                {
                    inputProgress.Value = (double)(peakValue * 500);
                }));
            }

            if (outputDevice != null)
            {
                theInfo   = AudioMeterInformation.FromDevice(outputDevice);
                peakValue = theInfo.GetPeakValue();
                outputProgress.Dispatcher.InvokeAsync((Action)(() =>
                {
                    outputProgress.Value = (double)(peakValue * 500);
                }));
            }
        }
Example #7
0
 private static bool IsAudioPlaying(MMDevice device)
 {
     using (var meter = AudioMeterInformation.FromDevice(device))
     {
         return(meter.PeakValue > 0);
     }
 }
Example #8
0
 public void CanCreateAudioMeterInformation()
 {
     using (var device = Utils.GetDefaultRenderDevice())
         using (var meter = AudioMeterInformation.FromDevice(device))
         {
         }
 }
Example #9
0
 public void CanGetAudioMeterInformationPeakValue()
 {
     using (var device = Utils.GetDefaultRenderDevice())
         using (var meter = AudioMeterInformation.FromDevice(device))
         {
             Console.WriteLine(meter.PeakValue);
         }
 }
 public AudioSessionInformation(AudioSessionControl2 session)
 {
     this.session      = session;
     this.process      = session.ProcessID;
     this.volumeObject = session.QueryInterface <SimpleAudioVolume>();
     this.audioMeter   = session.QueryInterface <AudioMeterInformation>();
     this.processName  = session.Process.ProcessName;
 }
        public void SetDevice(MMDevice Device)
        {
            CaptureDevice = Device;
            Meter         = Device.AudioMeterInformation;

            WasapiCapture = new WasapiCapture(Device);
            WasapiCapture.DataAvailable += WasapiCapture_DataAvailable;
            WasapiCapture.StartRecording();
        }
Example #12
0
 public void CanGetAudioMeterInformationChannelsPeaks()
 {
     using (var device = Utils.GetDefaultRenderDevice())
         using (var meter = AudioMeterInformation.FromDevice(device))
         {
             for (int i = 0; i < meter.MeteringChannelCount; i++)
             {
                 Console.WriteLine(meter[i]);
             }
         }
 }
 internal AudioSessionControl(IAudioSessionControl2 realAudioSessionControl)
 {
     IAudioMeterInformation _meters = realAudioSessionControl as IAudioMeterInformation;
     ISimpleAudioVolume _volume = realAudioSessionControl as ISimpleAudioVolume; 
     if (_meters != null)
         _AudioMeterInformation = new Windows7.AudioMeterInformation(_meters);
     if (_volume != null)
         _SimpleAudioVolume = new SimpleAudioVolume(_volume);
     _AudioSessionControl = realAudioSessionControl;
     
 }
Example #14
0
 public static double IsAudioPlaying(MMDevice device)
 {
     using (var meter = AudioMeterInformation.FromDevice(device))
     {
         if (meter.PeakValue > 0.1)
         {
             return(meter.PeakValue);
         }
         else
         {
             return(0);
         }
     }
 }
 public static bool IsAnyAudioPlaying()
 {
     //todo: implement goddamn SAMples!!!!!!!
     using var enumerator = new MMDeviceEnumerator();
     foreach (MMDevice device in enumerator.EnumAudioEndpoints(DataFlow.Render, DeviceState.Active))
     {
         using var meter = AudioMeterInformation.FromDevice(device);
         if (meter.PeakValue > 0)
         {
             return(true);
         }
     }
     return(false);
 }
Example #16
0
 private void setMute(bool mute, uint windowPid)
 {
     for (int i = 0; i < device.AudioSessionManager2.Sessions.Count; i++)
     {
         AudioSessionControl2 session = device.AudioSessionManager2.Sessions[i];
         uint pid = session.GetProcessID;
         AudioMeterInformation mi  = session.AudioMeterInformation;
         SimpleAudioVolume     vol = session.SimpleAudioVolume;
         if (pid == windowPid)
         {
             vol.Mute = mute;
         }
     }
 }
Example #17
0
        private void AudioDeviceChanged(object sender, AudioDeviceChangedEventArgs e)
        {
            _defaultRecording = e.DefaultRecording;
            _defaultPlayback  = e.DefaultPlayback;

            if (_defaultRecording != null)
            {
                _recordingInfo = AudioMeterInformation.FromDevice(_defaultRecording);
            }
            if (_defaultPlayback != null)
            {
                _playbackInfo = AudioMeterInformation.FromDevice(_defaultPlayback);
            }
        }
Example #18
0
 // Checks if audio is playing on a certain device
 public static bool IsAudioPlaying(MMDevice device)
 {
     try
     {
         using (var meter = AudioMeterInformation.FromDevice(device))
         {
             return(meter.PeakValue > 0);
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Example #19
0
        private void SetupAudio()
        {
            _defaultRecording = MMDeviceEnumerator.TryGetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);
            _defaultPlayback  = MMDeviceEnumerator.TryGetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);

            if (_defaultRecording != null)
            {
                _recordingInfo = AudioMeterInformation.FromDevice(_defaultRecording);
            }
            if (_defaultPlayback != null)
            {
                _playbackInfo = AudioMeterInformation.FromDevice(_defaultPlayback);
            }
        }
Example #20
0
        private void UpdateProcessMeterInformation()
        {
            foreach (var(process, meterInformation) in GetProcessMeters())
            {
                if (process.Id == _service.Gw2Process.Id)
                {
                    Logger.Debug("Found process associated audio session.");
                    _processMeterInformation = meterInformation;
                    break;
                }
            }

            _timeSinceCheck = 0;
        }
Example #21
0
        public static bool IsAudioPlaying(MMDevice device)
        {
            // Value ranges:
            // .3 to .6 is listening to music from an app at high volume.
            // .06 to .07 will be that same music at half the app volume level.
            // ~.022 will be that same music at quarter app volume level.
            // ~.007 will be that same music at 1/8th app volume level.
            // ~.001 will be barely audible.
            //
            // Take the average of the last 5 audio level samples and make sure
            // audio levels are consistently over the threshold
            //
            // Just to make things more complicated, for the user to actually be
            // listening to something, then the master volume should be at a decent
            // level. So at half level (0.6 to 0.7), and a .2 system volume level,
            // we are roughly at the .005 to .001 range of actual hearing levels.
            // rather than do the math, i opted for manually setting those by halving
            // audioVolumeThreshold when master volume < .5

            using (var meter = AudioMeterInformation.FromDevice(device))
            {
                var   masterVolume = AudioEndpointVolume.FromDevice(device).GetMasterVolumeLevelScalar();
                float modifiedAudioVolumeThreshold = audioVolumeThreshold;
                // Look at last 5 samples and average them.
                audioVolumeTracker.Add(meter.PeakValue);
                if (audioVolumeTracker.Count > 5)
                {
                    audioVolumeTracker.RemoveAt(0);
                }
                float audioVolumeAverage = audioVolumeTracker.Average();

                if (masterVolume < .50)
                {
                    modifiedAudioVolumeThreshold = modifiedAudioVolumeThreshold * 1.5f;
                }

                FileLogger.Log("-----------------+ Audio Debug Logs +----------------------------", 2);
                FileLogger.Log("Audio Meter Value  : " + meter.PeakValue, 2);
                FileLogger.Log("Audio Meter Average: " + audioVolumeAverage, 2);
                FileLogger.Log("Master Volume Level: " + masterVolume, 2);
                FileLogger.Log("Modified Threshold: " + modifiedAudioVolumeThreshold, 2);

                return(audioVolumeAverage > modifiedAudioVolumeThreshold);
            }
        }
Example #22
0
        private void GetMMD()
        {
            DW(1000);
            L.MMD = MMDE.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
            if (L.MMD == null)
            {
                return;
            }

            AEV = L.MMD.AudioEndpointVolume;
            AEV.OnVolumeNotification += AEV_OnVolumeNotification;

            L.MD = new MasterData(AEV.Mute, AEV.MasterVolumeLevelScalar);

            AMI = L.MMD.AudioMeterInformation;

            TryGetSs();
        }
Example #23
0
        private void initAudioRecorder()
        {
            if (audio != null)
            {
                audio.DataAvailable    -= Audio_DataAvailable;
                audio.RecordingStopped -= Audio_RecordingStopped;
                audio.Dispose();
            }
            if (blankplayer != null)
            {
                blankplayer.Dispose();
            }
            audio        = new WasapiLoopbackCapture(device);
            sourceFormat = audio.WaveFormat;
            if (sourceProvider == null)
            {
                sourceProvider           = new BufferedWaveProvider(sourceFormat);
                sourceProvider.ReadFully = false;
                wfto16prov         = new WaveFloatTo16Provider(sourceProvider);
                monovolumeprovider = new StereoToMonoProvider16(wfto16prov);
                formatconv         = new WaveFormatConversionProvider(new WaveFormat(24000, 16, 1), monovolumeprovider);
            }


            text_encoding.Text = sourceFormat.Encoding.ToString();
            //var client = device.AudioClient.AudioRenderClient;
            blankplayer = new WasapiOut(device, AudioClientShareMode.Shared, false, 0);

            silence = new SilenceProvider(sourceFormat).ToSampleProvider();

            AudioDevice_Text.ForeColor = Color.Black;

            try
            {
                blankplayer.Init(silence);
            }
            catch
            {
                AudioDevice_Text.ForeColor = Color.Red;
            }
            audio.DataAvailable    += Audio_DataAvailable;
            audio.RecordingStopped += Audio_RecordingStopped;
            AudioMonitor            = device.AudioMeterInformation;
        }
Example #24
0
        private void GetMMD()
        {
            M.D(1000, "GetMMD");
            L.MMD = CSCore.CoreAudioAPI.MMDeviceEnumerator.TryGetDefaultAudioEndpoint(CSCore.CoreAudioAPI.DataFlow.Render, CSCore.CoreAudioAPI.Role.Multimedia);
            if (L.MMD == null)
            {
                M.D(1001, M.Kind.ER, "MMD=null"); return;
            }

            AEV  = AudioEndpointVolume.FromDevice(L.MMD);
            AEVC = new AudioEndpointVolumeCallback();
            AEVC.NotifyRecived += AEV_NotifyRecived;
            AEV.RegisterControlChangeNotify(AEVC);
            L.MSD = new MasterData(AEV.IsMuted, AEV.MasterVolumeLevelScalar);

            AMI = AudioMeterInformation.FromDevice(L.MMD);
            //M.D(1008);
            //TryGetSs();
            M.D(1009);
        }
Example #25
0
        private void GetMMD()
        {
            DW(1000);
            L.MMD = CSCore.CoreAudioAPI.MMDeviceEnumerator.TryGetDefaultAudioEndpoint(CSCore.CoreAudioAPI.DataFlow.Render, CSCore.CoreAudioAPI.Role.Multimedia);
            if (L.MMD == null)
            {
                return;
            }

            AEV = AudioEndpointVolume.FromDevice(L.MMD);
            var aevc = new AudioEndpointVolumeCallback();

            aevc.NotifyRecived += Mepv_NotifyRecived;
            AEV.RegisterControlChangeNotify(aevc);
            L.MD = new MasterData(AEV.IsMuted, AEV.MasterVolumeLevelScalar);

            AMI = AudioMeterInformation.FromDevice(L.MMD);

            TryGetSs();
        }
Example #26
0
 public static bool IsAudioPlaying(MMDevice device)
 {
     using var meter = AudioMeterInformation.FromDevice(device);
     return(meter.PeakValue > 0.00005);
 }
Example #27
0
        public static SoundSourceInfo[] GetCurrentSoundSourceStatus()
        {
            /*
             #region temporary
             * bool foundActive = false;
             #endregion
             */

            List <SoundSourceInfo> soundSourceInfoList = new List <SoundSourceInfo>();
            SoundSourceInfo        soundSourceInfo     = null;

            // Note the AudioSession manager did not have a method to enumerate all sessions in windows Vista
            // this will only work on Win7 and newer.

            for (int i = 0; i < Device.AudioSessionManager.Sessions.Count; i++)
            {
                AudioSessionControl session = Device.AudioSessionManager.Sessions[i];

                soundSourceInfo = new SoundSourceInfo();

                soundSourceInfo.Session       = session;
                soundSourceInfo.StartDateTime = DateTime.Now; // might be overwritten in calling method

                /*
                 #region temporarys
                 * if (foundActive)
                 * {
                 *  session.SimpleAudioVolume.MasterVolume = 0; // TODO: mute it
                 *  continue;
                 * }
                 #endregion
                 */
                if (session.State == AudioSessionState.AudioSessionStateActive)  //TODO: include everything regardless of state?
                {
                    /*
                     #region temporary
                     * foundActive = true;
                     * if (session.SimpleAudioVolume.MasterVolume == 0)
                     *  session.SimpleAudioVolume.MasterVolume = 1.0f;
                     #endregion
                     */


                    soundSourceInfo.Pid = (int)session.ProcessID;

                    soundSourceInfo.IconPath                      = session.IconPath;
                    soundSourceInfo.DisplayName                   = session.DisplayName;
                    soundSourceInfo.SessionIdentifier             = session.SessionIdentifier;
                    soundSourceInfo.SessionInstanceIdentifier     = session.SessionInstanceIdentifier;
                    soundSourceInfo.IsSystemIsSystemSoundsSession = session.IsSystemIsSystemSoundsSession;
                    //soundSourceInfo.State = session.State;

                    Process p = Process.GetProcessById((int)session.ProcessID);
                    soundSourceInfo.ProcessName  = p.ProcessName;
                    soundSourceInfo.ProcessTitle = p.MainWindowTitle;
                    AudioMeterInformation mi  = session.AudioMeterInformation;
                    SimpleAudioVolume     vol = session.SimpleAudioVolume;

                    soundSourceInfo.Muted         = vol.Mute;
                    soundSourceInfo.ChannelVolume = session.SimpleAudioVolume.MasterVolume;
                    soundSourceInfo.CurrentVolume = session.AudioMeterInformation.MasterPeakValue;
                    soundSourceInfoList.Add(soundSourceInfo);
                }
            }

            SoundSourceInfo[] soundSourceInfos = soundSourceInfoList.ToArray();

            Array.Sort(soundSourceInfos, delegate(SoundSourceInfo info1, SoundSourceInfo info2)
            {
                return(info1.CompareTo(info2));
            }
                       );

            return(soundSourceInfos);
        }
 public float Audio(MMDevice device)
 {
     using AudioMeterInformation meter = AudioMeterInformation.FromDevice(device);
     meterinfo = meter.PeakValue;
     return(meterinfo);
 }
Example #29
0
        /// <summary>
        /// Creates the mixer channels - levels, slider, channel name, scale
        /// </summary>
        public static void CreateMixerChannels(MMDevice device)
        {
            //create arrays
            m_ChannelNames = new Label[10];
            m_Levels       = new Grid[10];
            m_LevelParents = new Grid[10];
            m_Sliders      = new Slider[10];
            m_Icons        = new System.Windows.Shapes.Rectangle[9];
            m_PeakMeters   = new AudioMeterInformation[10];

            //create mixer sliders
            for (int i = 0; i < 10; i++)
            {
                //main grid
                Grid grid = new Grid()
                {
                    Margin = Utils.ZeroMargin
                };

                //make grid child of mixer grid
                MainWindow.Instance.MixerGrid.Children.Add(grid);

                //skip the master channel
                if (i != 0)
                {
                    m_Icons[i - 1] = new System.Windows.Shapes.Rectangle()
                    {
                        Width               = 30,
                        Height              = 30,
                        VerticalAlignment   = VerticalAlignment.Top,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        Margin              = Utils.ZeroMargin
                    };

                    grid.Children.Add(m_Icons[i - 1]);
                }

                //label
                Label label = new Label()
                {
                    Content                    = "",
                    Foreground                 = new SolidColorBrush(ColorPalette.Accent),
                    FontFamily                 = new System.Windows.Media.FontFamily("Bahnschrift Bold"),
                    HorizontalAlignment        = HorizontalAlignment.Stretch,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    VerticalAlignment          = VerticalAlignment.Top,
                    Margin = Utils.ZeroMargin
                };

                //add to array
                m_ChannelNames[i] = label;

                //make label a child of grid
                grid.Children.Add(label);

                //add to array
                m_LevelParents[i] = grid;

                //slider
                Slider slider = new Slider()
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    //modify spacing on master channel
                    Margin = new Thickness()
                    {
                        Left = -32, Top = 36, Right = 0, Bottom = 16
                    },
                    VerticalAlignment = VerticalAlignment.Stretch,
                    Background        = null,
                    Width             = 22,
                    Orientation       = Orientation.Vertical,
                    Style             = (Style)Application.Current.Resources["MixerSlider"],
                    Maximum           = 100,
                    Value             = 70
                };

                //add to array
                m_Sliders[i] = slider;

                //setup channel volume
                if (i == 0)
                {
                    //master channel
                    m_MasterVolume     = AudioEndpointVolume.FromDevice(device);
                    m_Sliders[0].Value = m_MasterVolume.GetMasterVolumeLevelScalar() * 100f;

                    //master peak meter
                    m_PeakMeters[0] = AudioMeterInformation.FromDevice(device);
                }

                //value changed event
                int index = i;
                slider.ValueChanged += (sender, e) => Slider_ValueChanged(sender, e, i == 0, index);

                //make slider child of grid
                grid.Children.Add(slider);

                //levels
                //make a parent object
                m_InitialMargin = new Thickness()
                {
                    Left = 18, Top = 36, Right = 0, Bottom = 16
                };

                Grid level = new Grid()
                {
                    Margin = m_InitialMargin,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment   = VerticalAlignment.Stretch,
                    Width = 15
                };

                //make levels child of grid
                grid.Children.Add(level);

                //add to array
                m_Levels[i] = level;

                //levels shape
                System.Windows.Shapes.Rectangle bg = new System.Windows.Shapes.Rectangle()
                {
                    Fill = new SolidColorBrush(ColorPalette.Gray),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment   = VerticalAlignment.Stretch,
                    Margin = Utils.ZeroMargin
                };

                System.Windows.Shapes.Rectangle line = new System.Windows.Shapes.Rectangle()
                {
                    Fill = new SolidColorBrush(ColorPalette.Accent),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment   = VerticalAlignment.Top,
                    Margin = Utils.ZeroMargin,
                    Height = 2
                };

                //make shape child of levels grid
                level.Children.Add(bg);
                level.Children.Add(line);

                //scale grid
                UniformGrid scaleGrid = new UniformGrid()
                {
                    Columns = 1,
                    Rows    = 10,
                    //modify spacing on the master channel
                    Margin = new Thickness()
                    {
                        Left = 45, Top = 36, Right = 0, Bottom = 20
                    },
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment   = VerticalAlignment.Stretch,
                    Width = 5
                };

                //make scaleGrid child of grid
                grid.Children.Add(scaleGrid);

                //scale ticks
                for (int x = 0; x < 10; x++)
                {
                    System.Windows.Shapes.Rectangle tick = new System.Windows.Shapes.Rectangle()
                    {
                        Fill = new SolidColorBrush(ColorPalette.Gray),
                        HorizontalAlignment = HorizontalAlignment.Stretch,
                        VerticalAlignment   = VerticalAlignment.Center,
                        Margin = Utils.ZeroMargin,
                        Height = 2
                    };

                    //make ticks child of scale grid
                    scaleGrid.Children.Add(tick);
                }
            }


            //init channel volumes
            GetChannelVolumes();

            //set first channel
            SetChannelName(0, "Master");

            m_HasStarted = true;
        }
Example #30
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);
 }
Example #31
0
        static void Main(string[] args)
        {
            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
            MMDevice           device  = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

            // Note the AudioSession manager did not have a method to enumerate all sessions in windows Vista
            // this will only work on Win7 and newer.
            for (int i = 0; i < device.AudioSessionManager2.Sessions.Count; i++)
            {
                AudioSessionControl2 session = device.AudioSessionManager2.Sessions[i];
                if (session.State == AudioSessionState.AudioSessionStateActive)
                {
                    Console.WriteLine("Session :{0}", i);
                    Console.WriteLine("DisplayName: {0}", session.DisplayName);
                    Console.WriteLine("State: {0}", session.State);
                    Console.WriteLine("IconPath: {0}", session.IconPath);
                    Console.WriteLine("SessionIdentifier: {0}", session.GetSessionIdentifier);
                    Console.WriteLine("SessionInstanceIdentifier: {0}", session.GetSessionInstanceIdentifier);
                    Console.WriteLine("ProcessID: {0}", session.GetProcessID);
                    Console.WriteLine("IsSystemIsSystemSoundsSession: {0}", session.IsSystemSoundsSession);
                    Process p = Process.GetProcessById((int)session.GetProcessID);
                    Console.WriteLine("ProcessName: {0}", p.ProcessName);
                    Console.WriteLine("MainWindowTitle: {0}", p.MainWindowTitle);
                    AudioMeterInformation mi  = session.AudioMeterInformation;
                    SimpleAudioVolume     vol = session.SimpleAudioVolume;
                    Console.WriteLine("---[Hotkeys]---");
                    Console.WriteLine("M  Toggle Mute");
                    Console.WriteLine(",  Lower volume");
                    Console.WriteLine(",  Raise volume");
                    Console.WriteLine("Q  Quit");
                    int start = Console.CursorTop;
                    while (true)
                    {
                        //Draw a VU meter
                        int len = (int)(mi.MasterPeakValue * 79);
                        Console.SetCursorPosition(0, start);
                        for (int j = 0; j < len; j++)
                        {
                            Console.Write("*");
                        }
                        for (int j = 0; j < 79 - len; j++)
                        {
                            Console.Write(" ");
                        }
                        Console.SetCursorPosition(0, start + 1);
                        Console.WriteLine("Mute   : {0}    ", vol.Mute);
                        Console.WriteLine("Master : {0:0.00}    ", vol.MasterVolume * 100);
                        if (Console.KeyAvailable)
                        {
                            ConsoleKeyInfo key = Console.ReadKey();
                            switch (key.Key)
                            {
                            case ConsoleKey.M:
                                vol.Mute = !vol.Mute;
                                break;

                            case ConsoleKey.Q:
                                return;

                            case ConsoleKey.OemComma:
                                float curvol = vol.MasterVolume - 0.1f;
                                if (curvol < 0)
                                {
                                    curvol = 0;
                                }
                                vol.MasterVolume = curvol;
                                break;

                            case ConsoleKey.OemPeriod:
                                float curvold = vol.MasterVolume + 0.1f;
                                if (curvold > 1)
                                {
                                    curvold = 1;
                                }
                                vol.MasterVolume = curvold;
                                break;
                            }
                        }
                    }
                }
            }
            //If we end up here there where no open audio sessions to monitor.
            Console.WriteLine("No Audio sessions found");
        }
Example #32
0
        public AlarmSystem()
        {
            //_loggingEnabled = Trace.Listeners.Count > 1;
            Trace.TraceInformation("Alarm system init");
            Trace.Indent();
            state = States.Running;
            using (MMDeviceEnumerator enumerator = new MMDeviceEnumerator())
            {
                using (MMDevice device = enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Communications))
                {
                    _meter        = AudioMeterInformation.FromDevice(device);
                    _soundCapture = new WasapiCapture(true, AudioClientShareMode.Shared, 250)
                    {
                        Device = device
                    };
                    _soundCapture.Initialize();
                    _soundCapture.Start();
                    Trace.TraceInformation("Sound Capture OK");
                }
            }
            IWaveSource soundSource = GetSoundSource();

            soundSource = soundSource.Loop();
            _soundOut   = GetSoundOut();
            _soundOut.Initialize(soundSource);
            Trace.TraceInformation("Sound Out OK");

            captureMultiplier  = Properties.Settings.Default.Boost;
            delayBeforeAlarm   = Properties.Settings.Default.SafeScreamZone;
            delayBeforeOverlay = Properties.Settings.Default.AlertOverlayDelay;
            AlarmVolume        = (float)Properties.Settings.Default.Volume / 100;

            _systemSimpleAudioVolume = GetSimpleAudioVolume();
            SystemVolume             = (Properties.Settings.Default.VolumeSystem / 100f).Clamp(0, 1);
            KeepSystemVolume();

            _bgInputListener.WorkerSupportsCancellation = true;
            _bgInputListener.DoWork             += bgInputListener_DoWork;
            _bgInputListener.RunWorkerCompleted += bgInputListener_RunWorkerCompleted;

            _bgInputListener.RunWorkerAsync();
            Trace.TraceInformation("Background worker running");

            #region Timers

            _timerAlarmDelay       = new DispatcherTimer();
            _timerAlarmDelay.Tick += (s, args) =>
            {
                if (_timerAlarmDelayArgs.ElapsedTime.Seconds >= delayBeforeAlarm)
                {
                    _timerAlarmDelayArgs.alarmActive = true;
                    _timerAlarmDelay.Stop();
                    PlayAlarm();
                }

                OnUpdateTimerAlarmDelay(this, _timerAlarmDelayArgs);
                if (_timerAlarmDelay.Dispatcher.HasShutdownStarted)
                {
                    _timerAlarmDelayArgs = null;
                }
            };

            _timerOverlayShow       = new DispatcherTimer();
            _timerOverlayShow.Tick += (s, args) =>
            {
                if (_timerOverlayDelayArgs.ElapsedTime.Seconds >= delayBeforeOverlay)
                {
                    _timerOverlayDelayArgs.alarmActive = true;
                    _timerOverlayShow.Stop();
                    ShowAlertWindow();
                }
                OnUpdateTimerOverlayDelay(this, _timerOverlayDelayArgs);
                if (_timerOverlayShow.Dispatcher.HasShutdownStarted)
                {
                    _timerOverlayDelayArgs = null;
                }
            };

            _timerOverlayUpdate          = new DispatcherTimer();
            _timerOverlayUpdate.Interval = TimeSpan.FromMilliseconds(10);
            _timerOverlayUpdate.Tick    += (s, args) =>
            {
                _alertOverlay.Update();
                if (!_isMessageAlarmEnabled)
                {
                    _overlayWorking = false;
                }
                if (!_overlayWorking)
                {
                    _timerOverlayUpdate.Stop();
                    _alertOverlay.Dispose();
                    _alertOverlay = null;
                }
            };
            #endregion

            Trace.TraceInformation("Timers initialized");
            Trace.TraceInformation("Alarm System up and running!");
            Trace.Unindent();
        }