Пример #1
2
 public ShowAlarm()
 {
     InitializeComponent();
     MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
     device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
     iVolume = (int)(device.AudioEndpointVolume.MasterVolumeLevelScalar * 100); ;
 }
Пример #2
0
        public MainWindow()
        {
            InitializeComponent();

            _interceptor.Initialize();
            _interceptor.AddCallback(OnKeyAction);

            // Get the active microphone and speakers
            MMDeviceEnumerator deviceEnumerator = new MMDeviceEnumerator();
            MMDeviceCollection micList = deviceEnumerator.EnumerateAudioEndPoints(EDataFlow.eCapture, EDeviceState.DEVICE_STATE_ACTIVE);
            MMDeviceCollection speakerList = deviceEnumerator.EnumerateAudioEndPoints(EDataFlow.eRender, EDeviceState.DEVICE_STATE_ACTIVE);

            _activeSpeaker = deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
            _volumeRange = _activeSpeaker.AudioEndpointVolume.VolumeRange;
            _normalSpeakerVolume = _activeSpeaker.AudioEndpointVolume.MasterVolumeLevel;

            // ?? TODO: Add support for selecting applications that when their audio is above a certain level, turn down the audio of other applications.
            //DevicePeriod dp = _activeSpeaker.DevicePeriod;
            //Console.WriteLine(dp.DefaultPeriod);
            //Console.WriteLine(dp.MinimumPeriod);

            for (int i = 0; i < micList.Count; i++) {
                MMDevice mic = micList[i];
                _microphones.Add(mic);
                Console.WriteLine("Found microphone: " + mic.FriendlyName + " " + mic.ID);
            }

            for (int i = 0; i < speakerList.Count; i++) {
                MMDevice speaker = speakerList[i];
                _speakers.Add(speaker);
                Console.WriteLine("Found speaker: " + speaker.FriendlyName + " " + speaker.ID);
            }

            MinimizeToTray.Initialize(this, _muteIcon);
        }
Пример #3
0
        static SimpleAudioVolume getAudioVolume()
        {
            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.
            bool found = false;
            for (int i = 0; i < device.AudioSessionManager.Sessions.Count; i++)
            {
                AudioSessionControl session = device.AudioSessionManager.Sessions[i];

                if (Process.GetProcessById(Convert.ToInt32(session.ProcessID)).ProcessName.ToLower() == "spotify")
                {
                    found = true;
                    Out.WriteLine("FOUND SPOTIFY " + session.SessionIdentifier);
                    return session.SimpleAudioVolume;
                }
            }
            if (!found)
            {
                System.Windows.Forms.MessageBox.Show("Unable to find Spotify!\r\nAre you sure you're running win7 and spotify is enabled?", "MUTING FAILED", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return null;
            }
            return null;
        }
Пример #4
0
 /// <summary>
 /// 设备系统音量
 /// </summary>
 /// <param name="arg">音量百分比</param>
 public static void SetVolume(float arg)
 {
     MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
     MMDevice device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
     device.AudioEndpointVolume.Mute = false;
     device.AudioEndpointVolume.MasterVolumeLevelScalar = arg;
 }
Пример #5
0
 public WinApi()
 {
     MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
     device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
     //tbMaster.Value = (int)(device.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
     //device.AudioEndpointVolume.OnVolumeNotification += new AudioEndpointVolumeNotificationDelegate(AudioEndpointVolume_OnVolumeNotification);
     //timer1.Enabled = true;
 }
Пример #6
0
 public void Initialize(IntPtr handle)
 {
     MMDeviceEnumerator devEnum = new MMDeviceEnumerator ();
     m_device = devEnum.GetDefaultAudioEndpoint (EDataFlow.eRender, ERole.eMultimedia);
     NativeMethods.RegisterHotKey(handle, VolumeDown, NativeMethods.KeyModifiers.None, Keys.VolumeDown);
     NativeMethods.RegisterHotKey(handle, VolumeUp, NativeMethods.KeyModifiers.None, Keys.VolumeUp);
     NativeMethods.RegisterHotKey(handle, VolumeMute, NativeMethods.KeyModifiers.None, Keys.VolumeMute);
 }
        public VolumeDetectorVista()
        {
            devEnum = new MMDeviceEnumerator();
            defaultDevice =
              devEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

            defaultDevice.AudioEndpointVolume.OnVolumeNotification += new AudioEndpointVolumeNotificationDelegate(this.DelegateNotification);
        }
Пример #8
0
 /// <summary>
 /// Private constructor
 /// </summary>
 MasterVolume()
     : base("master", "Master Volume", DeviceCapabilities.Volume | DeviceCapabilities.SetMuted | DeviceCapabilities.GetMuted | DeviceCapabilities.LFEVolume)
 {
     var devices = new MMDeviceEnumerator();
     _defaultDevice = devices.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
     _defaultDevice.AudioEndpointVolume.OnVolumeNotification += AudioEndpointVolume_OnVolumeNotification;
     this.Save();
 }
        protected override void ProcessRecord()
        {
            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
            MMDeviceCollection devices = DevEnum.EnumerateAudioEndPoints(EDataFlow.eRender, EDeviceState.DEVICE_STATE_ACTIVE);

            for (int i = 0; i < devices.Count; i++)
            {
                WriteObject(new AudioDevice(i, devices[i]));
            }
        }
Пример #10
0
        public MainViewModel()
            : base()
        {
            visibilityTimer = new Timer(2000);
            visibilityTimer.Elapsed += visibilityTimerElapsed;
            visibilityTimer.AutoReset = false;

            deviceEnumerator = new MMDeviceEnumerator();
            device = deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
            device.AudioEndpointVolume.OnVolumeNotification += VolumeChanged;
        }
Пример #11
0
        public AppContext()
            : base()
        {
            bool ok = false;
            if (Environment.OSVersion.Version.Major > 5)
            {
                // Vista & higher
                ok = true;

                MMDeviceEnumerator devEnum = new MMDeviceEnumerator();
                this.defaultDevice = devEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
                this.defaultDevice.AudioEndpointVolume.OnVolumeNotification += new AudioEndpointVolumeNotificationDelegate(AudioEndpointVolume_OnVolumeNotification);
            }
            else
            {
                this.spkrVolumeControlID = MM.GetControlID(spkrComponent, spkrVolumeControl);
                this.spkrMuteControlID = MM.GetControlID(spkrComponent, spkrMuteControl);

                if (this.spkrVolumeControlID > 0)
                {
                    ok = true;

                    int v = MM.GetVolume(spkrVolumeControl, spkrComponent);
                    this.currentVolume = ConvertToPercentage(v);

                    this.hwnd = new Hwnd(WndProc);
                    int iw = (int)this.hwnd.Handle;

                    // ... and we can now activate the message monitor 
                    bool b = MM.MonitorControl(iw);
                }
            }

            if (ok)
            {
                NotificationType ntUp = new NotificationType(ntNameVolumeUp);
                NotificationType ntDown = new NotificationType(ntNameVolumeDown);
                NotificationType[] types = new NotificationType[] { ntUp, ntDown };
                Growl.Connector.Application app = new Growl.Connector.Application(appName);
                app.Icon = Properties.Resources.volumeter;

                this.growl = new GrowlConnector();
                this.growl.EncryptionAlgorithm = Cryptography.SymmetricAlgorithmType.PlainText;
                this.growl.Register(app, types);

                this.timer = new System.Timers.Timer(buffer);
                this.timer.AutoReset = false;
                this.timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            }
            else
            {
                MessageBox.Show("No speaker/line out component found to monitor");
            }
        }
Пример #12
0
        /// <summary>
        /// Initializes an instance of the class <see cref="AudioAnalyzer"/>
        /// </summary>
        public AudioAnalyzer()
        {
            this._fftDataBuffer = new float[1024];
            this._wasapiProcessCallback = new WASAPIPROC(this.WasapiProcessCallBack);

            Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_UPDATETHREADS, false);
            Bass.BASS_Init(0, 44100, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero);

            var devEnum = new MMDeviceEnumerator();
            this._mmAudioDevice = devEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
            this._mmAudioDevice.AudioEndpointVolume.OnVolumeNotification += this.AudioEndpointVolume_OnVolumeNotification;
        }
Пример #13
0
        public AudioInput()
        {
            _devices = new MMDeviceEnumerator();
            _devices.OnDeviceAdded += (s, e) => { UpdateDeviceInfo(); };
            _devices.OnDeviceRemoved += (s, e) => { UpdateDeviceInfo(true); };
            _devices.OnDeviceStateChanged += (s, e) => { UpdateDeviceInfo(); };
            _devices.OnPropertyValueChanged += (s, e) => { UpdateDeviceInfo(); };
            _devices.OnDefaultDeviceChanged += (s, e) => { UpdateDeviceInfo(); };

            _thread = new Thread(new ThreadStart(mainThread));
            _thread.Start();
        }
Пример #14
0
        public DataSources(List<Meter> meters)
        {
            prevFileCheck = new Dictionary<string, DateTime>();
            prevFileValue = new Dictionary<string, int>();

            monitor = new NetworkMonitor();
            adapters = monitor.Adapters;

            MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
            if (GlobalMemoryStatusEx(memStatus))
                TotalRAM = (int)((float)memStatus.ullTotalPhys / 1024 / 1024);

            bool startedMonitoring = false;

            foreach (Meter meter in meters)
                switch (meter.Data)
                {
                    case "CPU usage":
                        if (cpuCounter == null)
                        {
                            cpuCounter = new PerformanceCounter();
                            cpuCounter.CategoryName = "Processor";
                            cpuCounter.CounterName = "% Processor Time";
                            cpuCounter.InstanceName = "_Total";
                        }
                        break;
                    case "Available memory":
                    case "Used memory":
                        if (ramCounter == null)
                            ramCounter = new PerformanceCounter("Memory", "Available MBytes");
                        break;
                    case "Recycle bin file count":
                    case "Recycle bin size":
                        binQuery = new SHQUERYRBINFO();
                        break;
                    case "Download speed":
                    case "Upload speed":
                        if (!startedMonitoring)
                        {
                            monitor.StartMonitoring();
                            startedMonitoring = true;
                        }
                        break;
                    case "System volume":
                    case "Audio peak level":
                        if (audioDevice == null)
                        {
                            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
                            audioDevice = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
                        }
                        break;
                }
        }
Пример #15
0
        public MainWindow()
        {
            InitializeComponent();
            this.Topmost = true;
            this.WindowStartupLocation = WindowStartupLocation.Manual;
            this.Left = SystemParameters.PrimaryScreenWidth - 200;
            this.Top = SystemParameters.PrimaryScreenHeight - 100;

            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
            device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
            lblVolume.Content = (int)(device.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
            device.AudioEndpointVolume.OnVolumeNotification += new AudioEndpointVolumeNotificationDelegate(AudioEndpointVolume_OnVolumeNotification);
        }
        protected override void ProcessRecord()
        {
            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
            MMDeviceCollection devices = DevEnum.EnumerateAudioEndPoints(EDataFlow.eRender, EDeviceState.DEVICE_STATE_ACTIVE);
            MMDevice DefaultDevice = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

            for (int i = 0; i < devices.Count; i++)
            {
                if (devices[i].ID == DefaultDevice.ID)
                {
                    WriteObject(new AudioDevice(i, devices[i]));
                    return;
                }
            }
        }
Пример #17
0
 // Class constructor
 public MainForm()
 {
     this.WindowState = FormWindowState.Maximized;
     InitializeComponent();
     MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
     auddevice = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
     auddevice.AudioEndpointVolume.OnVolumeNotification += new AudioEndpointVolumeNotificationDelegate(AudioEndpointVolume_OnVolumeNotification);
     backgroundWorker1.RunWorkerAsync();
     glyphsImageList.ImageSize = new Size(32, 32);
     glyphList.LargeImageList = glyphsImageList;
     bordersToolStripMenuItem.Tag = VisualizationType.BorderOnly;
     namesToolStripMenuItem.Tag = VisualizationType.Name;
     imagesToolStripMenuItem.Tag = VisualizationType.Image;
     modelToolStripMenuItem.Tag = VisualizationType.Model;
 }
Пример #18
0
        public static Dictionary<string, string> GetAudioDevices()
        {
            Dictionary<string, string> audioDevices = new Dictionary<string, string>();

            audioDevices["Default Device"] = string.Empty;

            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
            MMDeviceCollection dc = DevEnum.EnumerateAudioEndPoints(EDataFlow.eRender, EDeviceState.DEVICE_STATE_ACTIVE);
            for (int i = 0; i < dc.Count; i++)
            {
                audioDevices[dc[i].FriendlyName] = dc[i].ID;
            }

            return audioDevices;
        }
        public static VolumePresenterViewModel Create()
        {
            MMDeviceEnumerator devEnum = new MMDeviceEnumerator();
            MMDevice defaultDevice = devEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

            return new VolumePresenterViewModel(
                    minValue: 0,
                    maxValue: 100,
                    setValue: (v) => defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar = (float)(v / 100.0),
                    getValue: Observable.FromEvent<AudioVolumeNotificationData>(
                                            o => defaultDevice.AudioEndpointVolume.OnVolumeNotification += new AudioEndpointVolumeNotificationDelegate(o),
                                            o => defaultDevice.AudioEndpointVolume.OnVolumeNotification -= new AudioEndpointVolumeNotificationDelegate(o))
                                        .Select(n=>n.MasterVolume)
                                         .Merge(Observable.Return(defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar))
                                         .Select(v=>(double)(v * 100.0)));
        }
Пример #20
0
        public Form1()
        {
            InitializeComponent();

            this.usbToolStripStatusLabel.Text = "RGB Bargraph Device Detached";

            // Serial stuff.
            try
            {
                //serSerialPort.PortName = "COM10";
                serSerialPort.Open();
                serAttach = true;
                this.usbToolStripStatusLabel.Text = "Serial port device attached.";

            }
            catch (Exception exe)
            {
                //MessageBox.Show("ERROR: " + exe);
                serAttach = false;
                this.usbToolStripStatusLabel.Text = "Serial port device not found...";

            }

            // Initialise the status strip text
            //this.usbToolStripStatusLabel.Text = "RGB Bargraph Device Detached";

            // Create the USB reference device object (passing VID and PID)
            theRgbBargraphDevice = new rgbBargraphDevice(0x04D8, 0x0100);

            // Register for device change notifications
            theRgbBargraphDevice.registerForDeviceNotifications(this.Handle);

            // Add a listener for usb events
            theRgbBargraphDevice.usbEvent +=
                new rgbBargraphDevice.usbEventsHandler(usbEvent_receiver);

            // Perform an initial search for the target device
            theRgbBargraphDevice.findTargetDevice();

            // Initialise the core audio API
            MMDeviceEnumerator devEnum = new MMDeviceEnumerator();
            defaultDevice = devEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

            // Set the starting value for the LED fade off speed
            theRgbBargraphDevice.setLedFadeOffSpeed((int)ledFadeOffSpeedTrackBar.Value);
        }
        public override bool Execute(string receivedText)
        {
            try
            {
                MMDeviceEnumerator devEnumerator = new MMDeviceEnumerator();
                MMDevice dev = devEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
                if(dev != null)
                {
                    dev.AudioEndpointVolume.Mute = !dev.AudioEndpointVolume.Mute;
                }

                return true;
            }
            catch(Exception e)
            {
                Log.d("Error in MuteCommand : " + e.ToString());
                return false;
            }
        }
Пример #22
0
        public MainModule()
        {
            MMDeviceEnumerator devEnum = new MMDeviceEnumerator();
            defaultDevice = devEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

            string html1 = "<html><body>Current volume: ";
            string html2 = "%.<br /><br /><a href='/p5'>+5</a><br /><a href='/p10'>+10</a><br /><a href='/m5'>-5</a><br /><a href='/m10'>-10</a>";

            Get["/"] = parameters =>
            {
                Console.WriteLine("/");
                return html1 + (defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100).ToString() + html2;
            };

            Get["/p5"] = parameters =>
                {
                    Console.WriteLine("+5");
                    defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar = validateVol(defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar + (float)0.05);
                    return html1 + (defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100).ToString() + html2;
                };

            Get["/p10"] = parameters =>
            {
                Console.WriteLine("+10");
                defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar = validateVol(defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar + (float)0.1);
                return html1 + (defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100).ToString() + html2;
            };

            Get["/m5"] = parameters =>
            {
                Console.WriteLine("-5");
                defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar = validateVol(defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar - (float)0.05);
                return html1 + (defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100).ToString() + html2;
            };

            Get["/m10"] = parameters =>
            {
                Console.WriteLine("-10");
                defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar = validateVol(defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar - (float)0.1);
                return html1 + (defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100).ToString() + html2;
            };
        }
Пример #23
0
        public MainWindow()
        {
            InitializeComponent();

            runner = new Thread(()=>
            {
                MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
                device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
                start = GetMSTime();
                initialAudioLevel = device.AudioEndpointVolume.MasterVolumeLevelScalar;

                while (true)
                {
                    double elapsed = (GetMSTime() - start)/1000;
                    double temporalVolume = (1.3+Math.Sin(elapsed*periodAdjust))/2.6;

                    device.AudioEndpointVolume.MasterVolumeLevelScalar = ((float)temporalVolume);
                    Debug.WriteLine("Volume was set to: " + ((float)temporalVolume));
                }
            });

            runner.Start();
        }
Пример #24
0
        public static Volume GetInstance()
        {
            var volume = new Volume();
            var processId = Process.GetCurrentProcess().Id;

            var devenum = new MMDeviceEnumerator();
            var device = devenum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

            for (var i = 0; i < device.AudioSessionManager.Sessions.Count; i++)
            {
                var session = device.AudioSessionManager.Sessions[i];
                if (session.ProcessID == processId)
                {
                    volume.simpleAudioVolume = session.SimpleAudioVolume;
                    volume.IsMute = session.SimpleAudioVolume.Mute;
                    volume.Value = (int)(session.SimpleAudioVolume.MasterVolume * 100);
                    // ToDo: ↓ これ入れて通知受けるようにすると、通知が走ったタイミングでアプリが落ちる。意味不明。誰か助けて。
                    //session.RegisterAudioSessionNotification(volume);
                    return volume;
                }
            }

            throw new Exception("Session is not found.");
        }
Пример #25
0
 public Form1()
 {
     InitializeComponent();
     
     MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
     device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
     this.Location = Properties.Settings.Default.location;
     this.TopMost = Properties.Settings.Default.TopMost;
     if (Properties.Settings.Default.variablevalue == true)
     {
         allowVariableMaxValueToolStripMenuItem.Checked = true;
         int zero = 1;
         lblMax.Text = zero.ToString();
         resetMaxValueToolStripMenuItem.Enabled = true;
     }
     else
     {
         allowVariableMaxValueToolStripMenuItem.Checked = false;
         int zero = 100;
         lblMax.Text = zero.ToString();
         resetMaxValueToolStripMenuItem.Enabled = false;
     }
     ChangeFontColors();
 }
Пример #26
0
        public static SoundInfo[] GetCurrentSoundInfo()
        {
            SoundInfo[] soundSourceInfos = new SoundInfo[0];

            try
            { // TODO: properly handle when headphones are used, etc.
                MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
                MMDevice device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

                List<SoundInfo> soundSourceInfoList = new List<SoundInfo>();
                SoundInfo soundInfo = 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];

                    soundInfo = new SoundInfo();

            //                    if (session.State == AudioSessionState.AudioSessionStateActive)
                    {
                        soundInfo.Pid = (int)session.ProcessID;

                        soundInfo.IconPath = session.IconPath;
                        soundInfo.DisplayName = session.DisplayName;
                        soundInfo.SessionIdentifier = session.SessionIdentifier;
                        soundInfo.SessionInstanceIdentifier = session.SessionInstanceIdentifier;
                        soundInfo.IsSystemSoundsSession = session.IsSystemSoundsSession;
                        //soundSourceInfo.State = session.State;

                        try
                        {
                            int pid = (int)session.ProcessID;
                            if (pid != 0)
                            {
                                string procName;
                                if (false == ProcNameDict.TryGetValue(pid, out procName))
                                {
                                    try
                                    {
                                        Process p = Process.GetProcessById(pid); //TO_DO: should remove processname and windowtitle from this class (but make sure that windowtitle gets updated at appropriate interval)
                                        ProcNameDict[pid] = p.ProcessName;
                                        ProcWindowTitleDict[pid] = p.MainWindowTitle;
                                        try
                                        {
                                            if (p.Modules.Count > 0)
                                                ProcFullPathDict[pid] = p.Modules[0].FileName;
                                            else
                                                ProcFullPathDict[pid] = "";
                                        }
                                        catch (Exception ex)
                                        {
                                            // WMI code from stackoverflow
                                            string query = "SELECT ExecutablePath, ProcessID FROM Win32_Process";
                                            System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query);

                                            foreach (ManagementObject item in searcher.Get())
                                            {
                                                object id = item["ProcessID"];
                                                object path = item["ExecutablePath"];

                                                if (path != null && id.ToString() == p.Id.ToString())
                                                {
                                                    ProcFullPathDict[pid] = path.ToString();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        System.Diagnostics.Debug.WriteLine(ex);
                                        ProcNameDict[pid] = "";
                                        ProcWindowTitleDict[pid] = "";
                                        ProcFullPathDict[pid] = "";
                                    }
                                }
                                soundInfo.ProcessName = ProcNameDict[pid];

                                soundInfo.WindowTitle = ProcWindowTitleDict[pid];
                                if (soundInfo.WindowTitle == "")
                                {
                                    try
                                    {
                                        Process proc = Process.GetProcessById(pid);
                                        soundInfo.WindowTitle = proc.MainWindowTitle;
                                        if (soundInfo.WindowTitle == "")
                                        {
                                            soundInfo.WindowTitle = proc.ProcessName;
                                        }
                                    }
                                    catch { }
                                }
                                soundInfo.ProcessFullPath = ProcFullPathDict[pid];
                                if ((soundInfo.ProcessFullPath == "") && (soundInfo.IsSystemSoundsSession == false))
                                {
                                    int x = 0;
                                    x++;
                                }
                            }
                            else
                            {
                                soundInfo.ProcessName = "";
                                soundInfo.WindowTitle = "System Sounds";
                                soundInfo.ProcessFullPath = "";
                            }
                        }
                        catch (Exception ex)
                        {
                            string msg = ex.Message;
                        }

                        AudioMeterInformation mi = session.AudioMeterInformation;
                        SimpleAudioVolume vol = session.SimpleAudioVolume;

                        soundInfo.Muted = vol.Mute;
                        soundInfo.MixerVolume = session.SimpleAudioVolume.MasterVolume;
                        //session.SimpleAudioVolume.MasterVolume = soundSourceInfo.ChannelVolume;
                        soundInfo.EmittedVolume = session.AudioMeterInformation.MasterPeakValue;
                        soundSourceInfoList.Add(soundInfo);
                    }
                }

                // Free up the memory
                IntPtr pointer = Marshal.GetIUnknownForObject(device);
                Marshal.Release(pointer);

                soundSourceInfos = soundSourceInfoList.ToArray();

                Array.Sort(soundSourceInfos, delegate(SoundInfo info1, SoundInfo info2)
                {
                    return info1.CompareTo(info2);
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex);
            }

            return soundSourceInfos;
        }
Пример #27
0
        /*
        public static float Duck(int pid) // will also mute; returns old volume
        {

        }
        public static void Unduck(int pid, float restoreToVolume) // will also unmute
        {

        }*/
        private static AudioSessionControl GetAudioSessionControl(string sessionInstanceIdentifier)
        {
            List<AudioSessionControl> audioSessionControlList = new List<AudioSessionControl>();
            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
            MMDevice device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

            List<SoundInfo> soundSourceInfoList = new List<SoundInfo>();
            for (int i = 0; i < device.AudioSessionManager.Sessions.Count; i++)
            {
                string procname = device.AudioSessionManager.Sessions[i].DisplayName;

                if (device.AudioSessionManager.Sessions[i].SessionInstanceIdentifier == sessionInstanceIdentifier)
                {
                    audioSessionControlList.Add(device.AudioSessionManager.Sessions[i]);
                }
            }

            if (audioSessionControlList.Count == 0)
                return null;
            if (audioSessionControlList.Count == 1)
                return audioSessionControlList[0];

            // TODO: this is a hack.  assumes that only one audiosessioncontrol plays sound.  Should refactor program to handle if there are more than one.
            for (int i = 0; i < audioSessionControlList.Count; i++)
            {
                if (audioSessionControlList[i].AudioMeterInformation.MasterPeakValue != 0)
                    return audioSessionControlList[i];
            }
            return audioSessionControlList[0];
        }
Пример #28
0
        // Set the volume by fading it in over time.  If user has changed volume manually, accept that.  Will need to add parameters to determine fade preferences. Advantage for doing this here: less discretized.  Also, means that only reason for looping is now volume sniffing.
        public static void SetVolume(string sessionInstanceIdentifier, float newVol, float fadeTimeInS, Delegate onUpdate)
        {
            float oldVol = -1;
            AudioSessionControl session = null;
            MMDevice device = null;

            if (sessionInstanceIdentifier == WinCoreAudioApiSoundServer.MasterVolSessionInstanceIdentifier)
            {
                MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
                device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

                oldVol = device.AudioEndpointVolume.MasterVolumeLevelScalar;
            }
            else
            {
                session = GetAudioSessionControl(sessionInstanceIdentifier);
                if (session != null)
                    oldVol = session.SimpleAudioVolume.MasterVolume;
                else
                {
                    int x = 0;
                    x++;
                }
            }
            if (oldVol >= 0)
            {
                DateTime fadeStartTime = DateTime.Now;
                //DateTime fadeEndTime = fadeStartTime.AddMilliseconds(Math.Abs(newVol - oldVol) * fadeTimeInS * 1000); // Updated so that if not going from 100 to 0, the fade time will be less (proportional to how much fading happens)
                DateTime fadeEndTime = fadeStartTime.AddMilliseconds(fadeTimeInS * 1000);

                DateTime now = fadeStartTime;
                while (now < fadeEndTime)
                {
                    float percent = (float)(1.0f - (fadeEndTime.Subtract(now)).TotalMilliseconds / (double)(fadeTimeInS * 1000));
                    //float percent = (float)(1.0f - (fadeEndTime.Subtract(now)).TotalMilliseconds / (double)(Math.Abs(newVol - oldVol) * fadeTimeInS * 1000));
                    if (percent >= 1.0f)
                        percent = 1.0f;
                    if (percent < 0)
                        percent = 0;
                    //MuteApp.SmartVolManagerPackage.SoundEventLogger.LogMsg(percent * 100 + "% pid: " + pid);
                    float currentVolume = oldVol + percent * (newVol - oldVol);
                    if (sessionInstanceIdentifier != WinCoreAudioApiSoundServer.MasterVolSessionInstanceIdentifier)
                        session.SimpleAudioVolume.MasterVolume = currentVolume;
                    else
                        device.AudioEndpointVolume.MasterVolumeLevelScalar = currentVolume;
                    System.Diagnostics.Debug.WriteLine("Fading volume to " + currentVolume);
                    //if (onUpdate != null)  jaredjared
                    //    onUpdate.DynamicInvoke();

                    System.Threading.Thread.Sleep(25);

                    float postSleepVol;
                    if (sessionInstanceIdentifier != WinCoreAudioApiSoundServer.MasterVolSessionInstanceIdentifier)
                        postSleepVol = session.SimpleAudioVolume.MasterVolume;
                    else
                        postSleepVol = device.AudioEndpointVolume.MasterVolumeLevelScalar;

                    if (postSleepVol != currentVolume)
                    {
                        // User manually adjusted volume
                        return;
                    }
                    now = DateTime.Now;
                    System.Diagnostics.Debug.WriteLine(sessionInstanceIdentifier + " Now = " + now);
                }

                if (sessionInstanceIdentifier != MasterVolSessionInstanceIdentifier)
                    session.SimpleAudioVolume.MasterVolume = newVol;
                else
                    device.AudioEndpointVolume.MasterVolumeLevelScalar = newVol;
            }
        }
Пример #29
0
        // negative pid is master volume
        public static void SetMute(string sessionInstanceIdentifier, bool muted)
        {
            if (sessionInstanceIdentifier == WinCoreAudioApiSoundServer.MasterVolSessionInstanceIdentifier)
            {
                MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
                MMDevice device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

                device.AudioEndpointVolume.Mute = muted;
            }
            else
            {
                AudioSessionControl session = GetAudioSessionControl(sessionInstanceIdentifier);
                if (session != null)
                    session.SimpleAudioVolume.Mute = muted;
                else
                {
                    int x = 0;
                    x++;
                }
            }
        }
Пример #30
0
 internal MMNotificationClient(MMDeviceEnumerator deviceEnumerator)
 {
     _DeviceEnumerator = deviceEnumerator;
 }
Пример #31
-1
 public MainForm()
 {
     InitializeComponent();
     MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
     _device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
     tbMaster.Value = (int)(_device.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
     _device.AudioEndpointVolume.OnVolumeNotification += new AudioEndpointVolumeNotificationDelegate(AudioEndpointVolume_OnVolumeNotification);
     syncLevelTimer.Enabled = true;
 }