public static bool GetSoundStatus(string sessionInstanceIdentifier, out float vol, out bool muted)
        {
            bool found = false;

            muted = false;
            vol   = 0.0f;

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

                muted = device.AudioEndpointVolume.Mute;
                vol   = device.AudioEndpointVolume.MasterVolumeLevelScalar;
                found = true;
            }
            else
            {
                AudioSessionControl session = GetAudioSessionControl(sessionInstanceIdentifier);
                if (session != null)
                {
                    muted = session.SimpleAudioVolume.Mute;
                    vol   = session.SimpleAudioVolume.MasterVolume;
                    found = true;
                }
            }
            return(found);
        }
        private void btnRiotClientServicesAudio_Click(object sender, RoutedEventArgs e)
        {
            var task = Task.Run(() =>
            {
                return(AudioSessionsHelper.GetAudioSessionByProcessName(riotServicesProcessName));
            });

            task.Wait();

            if (task.Result == null)
            {
                rioServicesStrip.AudioStateTextBox = "Not found";
                return;
            }

            if (riotServicesAudioSession != null)
            {
                riotServicesAudioSession.Dispose();
            }

            riotServicesAudioSession = task.Result;

            rioServicesStrip.AudioStateTextBox = AudioSessionsHelper.GetStringAudioState(riotServicesAudioSession.State);
            rioServicesStrip.AudioMutedTextBox = AudioSessionsHelper.GetStringFromMuted(riotServicesAudioSession.Mute);

            riotServicesAudioSession.StateChanged        += riotServicesAudioSession_StateChanged;
            riotServicesAudioSession.SimpleVolumeChanged += riotServicesAudioSession_SimpleVolumeChanged;
            SubscribeMouseEvents();
        }
Example #3
0
        private void AddSession(AudioSessionControl asc, bool safe = true)
        {
            var n = asc.DisplayName;

            DW(31); DW(Thread.CurrentThread.GetHashCode());
            if (!safe)
            {
                DW(Dispatcher);
                Dispatcher?.Invoke(() =>
                {
                    DW(32); DW(Thread.CurrentThread.GetHashCode());
                    L.SNames.Add(n);
                });
            }
            else
            {
                DW(32); DW(Thread.CurrentThread.GetHashCode());
                L.SNames.Add(n);
            }
            DW(3); DW(Thread.CurrentThread.GetHashCode());
            //asc.SessionDisconnected += Asc_SessionDisconnected;
            //asc.StateChanged += Asc_StateChanged;
            var s = new Session(asc.BasePtr, L);

            s.Offline += S_Offline;
            SL2.Add(s);
        }
Example #4
0
        // Helpers
        private bool GetSetMute(bool Get = true, bool mute = false)
        {
            lock (locker)
            {
                try
                {
                    for (int i = 0; i < deviceInit.AudioSessionManager.Sessions.Count; i++)
                    {
                        AudioSessionControl session = deviceInit.AudioSessionManager.Sessions[i];
                        if (processId == session.GetProcessID)
                        {
                            deviceVol = device.AudioEndpointVolume;

                            if (Get)
                            {
                                return(session.SimpleAudioVolume.Mute | deviceVol.Mute);
                            }
                            session.SimpleAudioVolume.Mute = mute;
                            if (deviceVol.Mute)
                            {
                                deviceVol.Mute = false;
                            }

                            break;
                        }
                    }
                } catch (Exception) { }
            }

            return(false);
        }
        private void btnAttachValorantAudio_Click(object sender, RoutedEventArgs e)
        {
            var task = Task.Run(() =>
            {
                return(AudioSessionsHelper.GetAudioSessionByProcessName(valorantProcessName));
            });

            task.Wait();

            if (task.Result == null)
            {
                valorantStrip.AudioStateTextBox = "Not found";
                return;
            }

            if (valorantAudioSession != null)
            {
                valorantAudioSession.Dispose();
            }

            valorantAudioSession = task.Result;

            valorantStrip.AudioStateTextBox = AudioSessionsHelper.GetStringAudioState(valorantAudioSession.State);
            valorantStrip.AudioMutedTextBox = AudioSessionsHelper.GetStringFromMuted(valorantAudioSession.Mute);

            valorantAudioSession.StateChanged        += valorantAudioSession_StateChanged;
            valorantAudioSession.SimpleVolumeChanged += valorantAudioSession_SimpleVolumeChanged;
            windowHooker.Init();
        }
Example #6
0
        private List <AudioSession> GetSessions()
        {
            List <AudioSession> controls         = new List <AudioSession>();
            MMDeviceEnumerator  deviceEnumerator = new MMDeviceEnumerator();
            MMDeviceCollection  deviceCollection = deviceEnumerator.EnumerateAudioEndPoints(EDataFlow.eRender, EDeviceState.DEVICE_STATE_ACTIVE);
            string devName;

            for (int i = 0; i < deviceCollection.Count; i++)
            {
                MMDevice device = deviceCollection[i];
                devName = device.FriendlyName;
                for (int j = 0; j < device.AudioSessionManager.Sessions.Count; j++)
                {
                    AudioSessionControl session = device.AudioSessionManager.Sessions[j];
                    Process             p;
                    try
                    {
                        p = Process.GetProcessById((int)session.ProcessID);
                    }
                    catch
                    {
                        p = Process.GetProcesses()[0];
                    }
                    if (p.ProcessName == _processName)
                    {
                        controls.Add(new AudioSession(session, devName));
                    }
                }
            }
            return(controls);
        }
Example #7
0
        /// <summary>
        /// Handles wrapping the session into a higher level object, registering
        /// it in the service and notifying of the event.
        /// </summary>
        /// <param name="session_"></param>
        private void OnSessionCreated(AudioSessionControl session_)
        {
            var session = new AudioSession(session_);

            AppLogging.DebugLog(nameof(OnSessionCreated), session.SessionIdentifier, session.DisplayName, session.Id.ToString());
            RegisterSession(session);
        }
        /// <summary>
        /// 找到我们要找的程序
        /// </summary>
        /// <param name="exeName">exe程序的名字</param>
        /// <param name="isMute">静音还是不静音</param>
        private void FindTheApplication(string exeName, bool isMute)
        {
            //判断这个程序是不是我们要的
            for (int i = 0; i < audioSessionManager.Sessions.Count; i++)
            {
                AudioSessionControl app = sessions[i];
                string sIdentifier      = app.SessionIdentifier;

                if (isTheAppWeNeed(sIdentifier, exeName))
                {
                    //app.SimpleAudioVolume.MasterVolume=0;

                    app.SimpleAudioVolume.Mute = isMute;//设置静音状态
                    if (isMute)
                    {
                        //label3.Text = "静音成功!";
                    }
                    else
                    {
                        //label3.Text = "取消静音成功!";
                    }

                    return;
                }
            }
            //label3.Text = "没有找到该exe程序的音量控制实体";
        }
Example #9
0
        private SoundMixer()
        {
            Channels = new Channel[0x10];
            for (byte i = 0; i < 0x10; i++)
            {
                Channels[i] = new Channel(i);
            }

            Mutes = new bool[0x10];

            buffer = new BufferedWaveProvider(new WaveFormat(65456, 16, 2))
            {
                DiscardOnBufferOverflow = true,
                BufferLength            = 0x5540
            };
            @out = new WasapiOut();
            @out.Init(buffer);
            SessionCollection sessions = new MMDeviceEnumerator().GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).AudioSessionManager.Sessions;
            int id = System.Diagnostics.Process.GetCurrentProcess().Id;

            for (int i = 0; i < sessions.Count; i++)
            {
                AudioSessionControl session = sessions[i];
                if (session.GetProcessID == id)
                {
                    appVolume = session;
                    appVolume.RegisterEventClient(this);
                    break;
                }
            }
            @out.Play();
        }
        /// <summary>
        /// 开启程序时就执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            //初始化设备
            MMDeviceEnumerator devEnum = new MMDeviceEnumerator();

            device = devEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

            //label1.Text = "当前音量:" + Convert.ToInt32(device.AudioEndpointVolume.MasterVolumeLevelScalar * 100.0f);


            //获取所有程序声音的管理器
            audioSessionManager = device.AudioSessionManager;
            sessions            = audioSessionManager.Sessions;

            //显示所有程序的SessionIdentifier
            label1.Text = "当前应用音量的个数" + audioSessionManager.Sessions.Count +
                          "。当前所有音频程序的SessionIdentifier:\n";
            for (int i = 0; i < audioSessionManager.Sessions.Count; i++)
            {
                AudioSessionControl app = sessions[i];
                string sIdentifier      = app.SessionIdentifier;
                label1.Text += app.SessionIdentifier + "\n";
            }


            Thread a = new Thread(CheckTxT);

            a.IsBackground = true;
            a.Start();
            //CheckTxT();
        }
        /// <summary>
        /// Handles wrapping the session into a higher level object, registering
        /// it in the service and notifying of the event.
        /// </summary>
        /// <param name="session_"></param>
        private void OnSessionCreated(AudioSessionControl session_)
        {
            var session = new AudioSession(session_);

            m_Logger.Debug(string.Join("\t", nameof(OnSessionCreated), session.SessionIdentifier, session.DisplayName, session.Id));
            RegisterSession(session);
        }
Example #12
0
        void AddVolumePanel(AudioSessionControl session)
        {
            var panel = new VolumePanel(DeviceVolumePanel.Device, session);

            AppVolumePanels.Add(panel);
            flowLayoutPanelApps.Controls.Add(panel);
        }
Example #13
0
        private void Dispose(bool disposing)
        {
            if (_isDisposed)
            {
                return;
            }

            _timerSubscription?.Dispose();
            _meterInformation.Dispose();
            _simpleAudioVolume.Dispose();
            _deviceMutedSubscription.Dispose();
            _muteChanged.Dispose();
            _stateChanged.Dispose();
            _disconnected.Dispose();
            _volumeChanged.Dispose();
            _peakValueChanged.Dispose();


            //Run this on the com thread to ensure it's disposed correctly
            ComThread.BeginInvoke(() =>
            {
                AudioSessionControl.UnregisterAudioSessionNotification(this);
            }).ContinueWith(x =>
            {
                _audioSessionControl.Dispose();
            });

            GC.SuppressFinalize(this);
            _isDisposed = true;
        }
 private void HandleNewSession(AudioSessionControl newSession, String filename)
 {
     if (filename.EndsWith(exeSuffix, StringComparison.OrdinalIgnoreCase) && (session == null || newSession.AudioMeterInformation.MasterPeakValue >= session.AudioMeterInformation.MasterPeakValue))
     {
         session = newSession;
     }
 }
Example #15
0
        /// <summary>
        /// ウマ娘ウィンドウの音量が0になって再び0以上になるまで待機します。
        /// </summary>
        /// <param name="timeOutMillisecond">タイムアウト時間ミリ秒</param>
        private void WaitUmaWindowAvailable(Process process, int timeOutMillisecond)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            MMDevice device = null;

            try
            {
                //ウマ娘セッションの検索
                AudioSessionControl umamusumeSession = null;
                while (umamusumeSession == null)
                {
                    using (MMDeviceEnumerator DevEnum = new MMDeviceEnumerator())
                    {
                        device?.Dispose();
                        device = DevEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
                    }
                    AudioSessionManager sessionManager = device.AudioSessionManager;
                    var sessions = sessionManager.Sessions;
                    for (int j = 0; j < sessions.Count; j++)
                    {
                        if (sessions[j].GetProcessID == process.Id)
                        {
                            umamusumeSession = sessions[j];
                            break;
                        }
                    }
                }

                //0になるまで待機(0以外の間ループ)
                while (umamusumeSession.AudioMeterInformation.MasterPeakValue > 0.005)
                {
                    Thread.Sleep(10);
                    if (stopwatch.ElapsedMilliseconds > timeOutMillisecond)
                    {
                        return;
                    }
                }

                //0以上になるまで待機(0の間ループ)
                while (umamusumeSession.AudioMeterInformation.MasterPeakValue < 0.1)
                {
                    Thread.Sleep(10);
                    if (stopwatch.ElapsedMilliseconds > timeOutMillisecond)
                    {
                        return;
                    }
                }
            }
            finally
            {
                if (device != null)
                {
                    device.Dispose();
                }
            }
        }
 public SoundDevice(DeviceController deviceController, bool isMasterVolumeForDevice, MMDevice device, AudioSessionControl session)
 {
     this.IsMasterVolumeControlForDevice = isMasterVolumeForDevice;
     this._device      = device;
     this._session     = session;
     _deviceController = deviceController;
     _session.RegisterEventClient(this);
 }
Example #17
0
 private void RemoveSession(AudioSessionControl asc)
 {
     M.D(22000, "RemoveSession");
     //SS.Remove(asc as Session);
     L.SSD.Remove(L.SSD.FirstOrDefault(s => s.BasePtr == asc.BasePtr));
     L.SSN.Remove(asc.DisplayName);
     SessionRemoved?.Invoke(this, new SessionEventArgs(asc.BasePtr));
     M.D(22001, $"# SS:{SS.Count}, SSD:{L.SSD.Count}, SSN:{L.SSN.Count}");
 }
Example #18
0
        public void AddHandler(AudioSessionControl session)
        {
            string currentId = session.SessionInstanceIdentifier + session.ProcessID;

            if (!IDs.Exists(id => id == currentId))
            {
                session.RegisterAudioSessionNotification(Handler);
                IDs.Add(currentId);
            }
        }
Example #19
0
        private static int GetSessionPID(AudioSessionControl session)
        {
            int PID;

            using (var audiosession = session.QueryInterface <AudioSessionControl2>())
            {
                audiosession.GetProcessIdNative(out PID);
            }
            return(PID);
        }
Example #20
0
        private void AddNewSession(AudioSessionControl asc)
        {
            //L.Ss.Add(new SessionData(asc.BasePtr));
            var s = new Session(asc.BasePtr, L);

            //s.Offline += S_Offline;
            //s.Online += S_Online;
            SS.Add(s);
            DW($"Ss#:{L.Ss.Count} {SS.Count}");
        }
        private AudioSessionWrapper RegisterSession(AudioSessionControl session)
        {
            var wrapper = new AudioSessionWrapper(session);

            _wrappers[wrapper.ProcessID] = wrapper;

            wrapper.SimpleVolumeChanged += OnSimpleVolumeChanged;
            wrapper.SessionDisconnected += OnSessionRemoved;

            return(wrapper);
        }
Example #22
0
        private static void AudioVolume(AudioSessionControl session, int volume)
        {
            SimpleAudioVolume simpleVolume = session.QueryInterface <SimpleAudioVolume>();

            simpleVolume.MasterVolume = (float)volume / 100;

            bool muted = simpleVolume.IsMuted;

            simpleVolume.IsMuted = !muted;
            simpleVolume.IsMuted = muted;
        }
Example #23
0
        private static void AudioVolume(AudioSessionControl session)
        {
            SimpleAudioVolume simpleVolume = session.QueryInterface <SimpleAudioVolume>();

            simpleVolume.MasterVolume = 1.0f;

            bool muted = simpleVolume.IsMuted;

            simpleVolume.IsMuted = !muted;
            simpleVolume.IsMuted = muted;
        }
Example #24
0
 /*
  * Uses CoreAudioApi to get Spotify's Audio session associated with the process id given.
  */
 public AudioSessionControl getSpotifyAudioSession(int spotProcId)
 {
     for (int i = 0; i < defaultDevice.AudioSessionManager.Sessions.Count; i++) // possible TODO: good spot for binary search if there are large numbers of spotify processes.
     {
         AudioSessionControl currASC = defaultDevice.AudioSessionManager.Sessions[i];
         if (currASC.ProcessID == spotProcId)
         {
             return(currASC);
         }
     }
     return(null);
 }
Example #25
0
 private static void PrintSessionName(AudioSessionControl sessionControl)
 {
     if (!string.IsNullOrEmpty(sessionControl.DisplayName))
     {
         Console.WriteLine("Name: " + sessionControl.DisplayName);
     }
     else
     {
         AudioSessionControl2 sessionControl2 = sessionControl.QueryInterface <AudioSessionControl2>();
         Console.WriteLine("Name: " + sessionControl2.Process.ProcessName);
     }
 }
Example #26
0
        public AudioSession(AudioSessionControl session)
        {
            _session = session;
            _session.RegisterAudioSessionNotification(_events);

            _session2    = _session.QueryInterface <AudioSessionControl2>();
            _simpleAudio = _session.QueryInterface <SimpleAudioVolume>();

            _events.StateChanged        += OnStateChanged;
            _events.SimpleVolumeChanged += OnVolumeChanged;

            UpdateDisplayName();
        }
Example #27
0
        private void AddNewSession(AudioSessionControl asc)
        {
            M.D(21000, "AddNewSession");
            var s = new Session(asc.BasePtr, ref L);

            s.Offline += S_Offline;
            s.Online  += S_Online;
            SS.Add(s);
            L.SSD.Add(new SessionData(asc.BasePtr, asc.DisplayName));
            L.SSN.Add(s.DisplayName);
            SessionAdded?.Invoke(this, new SessionEventArgs(asc.BasePtr));
            M.D(21001, $"# SS:{SS.Count}, SSD:{L.SSD.Count}, SSN:{L.SSN.Count}");
        }
            private void HandleNewSession(AudioSessionControl newSession, String filename)
            {
                VolumeChannel proxied;

                if (_proxied.TryGetTarget(out proxied))
                {
                    proxied.HandleNewSession(newSession, filename);
                }
                else
                {
                    Dispose();
                }
            }
Example #29
0
    static void FindAudioSession(bool isSilent = false)
    {
        if (!isSilent)
        {
            Console.WriteLine("Finding Spotify audio session...");
        }
        var sessionManager    = GetDefaultAudioSessionManager2(DataFlow.Render);
        var sessionEnumerator = sessionManager.GetSessionEnumerator();

        foreach (var session in sessionEnumerator)
        {
            // looks through all the active sessions and looks for "spotify" in the `Process` toString
            try
            {
                var sesInf = session.QueryInterface <AudioSessionControl2>();
                if (sesInf.Process.ToString().ToLower().Contains("spotify"))
                {
                    Console.Write("\r");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine(String.Format("{0,-80}", "Spotify session found"));
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("Process ID: " + sesInf.ProcessID);
                    spotifyAudioSession = session;
                    spotifyProcess      = spotifyAudioSession.QueryInterface <AudioSessionControl2>().Process;
                    break;
                }
            }
            catch (InvalidOperationException)
            {
                // this can happen if the current session (in the loop, not Spotify) exited before we check its name
                // this will resault in the following "System.InvalidOperationException: Process has exited, so the requested information is not available."
                continue;
            }
        }
        if (spotifyAudioSession == null)
        {
            if (!isSilent)
            {
                Console.ForegroundColor = ConsoleColor.Red;
            }
            if (!isSilent)
            {
                Console.WriteLine("Spotify not found.");
            }
            if (!isSilent)
            {
                Console.WriteLine("either it's not running or it doesn't have an active audio session, try playing something");
            }
            Console.ForegroundColor = ConsoleColor.Gray;
        }
    }
Example #30
0
        public AudioSessionWrapper(AudioSessionControl session)
        {
            _events = new AudioSessionEvents();
            _events.StateChanged        += OnStateChanged;
            _events.SimpleVolumeChanged += OnSimpleVolumeChanged;

            _session = session;
            _session.RegisterAudioSessionNotification(_events);

            _session2    = _session.QueryInterface <AudioSessionControl2>();
            _simpleAudio = _session.QueryInterface <SimpleAudioVolume>();

            _isNotifyEnabled = true;
        }