/// <summary> /// Populates the session dictionary /// </summary> /// <param name="device">Speaker MMDevice</param> private void populateAudioSessions(MMDevice device) { //Master volume (Audio Device) session AudioSession deviceSession = getMasterAudioSessionObject(device); AudioSessions.Add(deviceSession.id, deviceSession); //Process sessions for (int i = 0; i < device.AudioSessionManager2.Sessions.Count; i++) { AudioSessionControl2 sessionControl = device.AudioSessionManager2.Sessions[i]; if (setAudioSessionEventHandlers(sessionControl)) { AudioSession foundSession = getAudioSessionObject(sessionControl); Console.WriteLine("\n" + foundSession.ToString()); Console.WriteLine("state: " + sessionControl.State.ToString()); if (!AudioSessions.ContainsKey(foundSession.id)) { AudioSessions.Add(foundSession.id, foundSession); } else { if (sessionControl.State == AudioSessionState.AudioSessionStateActive) { AudioSessions[foundSession.id] = foundSession; } } } } }
/// <summary> /// アプリケーションの音量をdouble型で取得 /// </summary> /// <param name="processId">プロセスID</param> /// <returns> /// 音量(0~1) as double. /// -1 means no audio. /// </returns> public static double GetVolume(int processId) { double volume = -1; Process process = Process.GetProcessById(processId); // Call from a new thread. Task.Run(() => GetAudioSessions((AudioSessionControl session) => { try { AudioSessionControl2 session2 = session.QueryInterface <AudioSessionControl2>(); // // Ideal is branch if the process id is equal. (not working) // if (session2.ProcessID == processId) // モジュールのパスが同じであるか if (process.MainModule != null && session2.Process.MainModule.FileName == process.MainModule.FileName) { SimpleAudioVolume audioVolume = session.QueryInterface <SimpleAudioVolume>(); volume = audioVolume.MasterVolume; } } catch (Exception e) { // Usually Win32Exception. Console.WriteLine(e.Message); } })); return(volume); }
private static bool SetIsMuted(AudioSessionControl2 audioSession, bool shouldMute) { try { if (audioSession == null) { Logger.Instance.LogMessage(TracingLevel.ERROR, "IsMuted failed - audioSession is null"); return(false); } var volumeObj = audioSession.QueryInterface <SimpleAudioVolume>(); if (volumeObj == null) { Logger.Instance.LogMessage(TracingLevel.WARN, $"QueryInterface for IsMuted failed for {audioSession?.DisplayName}"); return(false); } volumeObj.IsMuted = shouldMute; return(true); } catch (Exception ex) { Logger.Instance.LogMessage(TracingLevel.WARN, $"IsMuted exception {ex}"); return(false); } }
private static bool SetVolume(AudioSessionControl2 audioSession, float volume) { try { if (audioSession == null) { Logger.Instance.LogMessage(TracingLevel.ERROR, "SetVolume failed - audioSession is null"); return(false); } var volumeObj = audioSession.QueryInterface <SimpleAudioVolume>(); if (volumeObj == null) { Logger.Instance.LogMessage(TracingLevel.WARN, $"QueryInterface for SetVolume failed for {audioSession?.DisplayName}"); return(false); } volumeObj.MasterVolume = volume; return(true); } catch (Exception ex) { Logger.Instance.LogMessage(TracingLevel.WARN, $"SetVolume exception {ex}"); return(false); } }
public void HandleSessionChanged(object sender, AudioSessionChangedType type) { AudioSessionControl2 sessionControl = (AudioSessionControl2)sender; AudioSession changedSession = getAudioSessionObject(sessionControl); if (type == AudioSessionChangedType.DisplayName) { AudioSessions[changedSession.id].title = (changedSession.title == "" ? Process.GetProcessById(changedSession.pid).ProcessName : sessionControl.DisplayName); } else if (type == AudioSessionChangedType.Volume) { AudioSessions[changedSession.id].volume = changedSession.volume; AudioSessions[changedSession.id].mute = changedSession.mute; } if (Main.LOG_EVENTS) { Console.WriteLine("\nSession Volume Object Changed: " + changedSession.ToString()); } if (OnAudioSessionEdited != null) { OnAudioSessionEdited(changedSession); } }
public void Dispose() { try { // Do unregistration, can throw if (_events != null) { _events.StateChanged -= OnStateChanged; _events.SimpleVolumeChanged -= OnVolumeChanged; Session.UnregisterAudioSessionNotification(_events); } } catch { } // Do disposal chains, each can throw try { _session2.Dispose(); } catch { } try { Session.Dispose(); } catch { } // Set to null _simpleAudio = null; _session2 = null; Session = null; }
// Break if one critera is true- if a Spotify audio session can no longer be found public bool ToBreak() { // If we can no longer find Spotify as an audio session, return true Boolean found = false; sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render); sessionEnumerator = sessionManager.GetSessionEnumerator(); Assert.IsNotNull(sessionEnumerator); foreach (AudioSessionControl session in sessionEnumerator) { if (session == null) { break; } sessionControl = session.QueryInterface <AudioSessionControl2>(); if (sessionControl == null) { break; } if (sessionControl.SessionIdentifier.Contains("Spotify.exe")) { spotifyControl = sessionControl; programGUI.setSpotify(session); found = true; break; } } if (!found) { programGUI.setSpotify(null); sessionControl = null; return(true); } return(false); }
public async void TestToUnmuteAsync(Object stateInfo) { // If Spotify was closed, return if (ToBreak()) { return; } spotifyControl = programGUI.getSpotify().QueryInterface <AudioSessionControl2>(); spotifyVolume = spotifyControl.QueryInterface <SimpleAudioVolume>(); if (!spotifyControl.Process.MainWindowTitle.Equals("Advertisement") && !spotifyControl.Process.MainWindowTitle.Equals("Spotify")) { // If Spotify is muted if (spotifyVolume.IsMuted) { // Save song name programGUI.setSongTitle(spotifyControl.Process.MainWindowTitle); // Wait for the presumed advert to completely stop playing await programGUI.pauseAsync(); // Unmute the audio session spotifyVolume.IsMuted = false; // Display advert prevented & the song now playing programGUI.setDisplayVariable("Advert prevented..." + System.Environment.NewLine + "Now playing... - " + programGUI.getSongTitle() + System.Environment.NewLine + "One song since an advert..."); programGUI.setSongsAfterAdvertChange(1); } } }
private AudioSession getAudioSessionObject(AudioSessionControl2 asc) { int _pid = (int)asc.GetProcessID; string displayName = asc.DisplayName; if (_pid == 0 || displayName.Contains(@"\AudioSrv.Dll")) { displayName = "System"; } else if (displayName == "") { try { displayName = Process.GetProcessById(_pid).ProcessName; } catch { displayName = "Application"; } } return(new AudioSession() { mute = asc.SimpleAudioVolume.Mute, pid = _pid, title = displayName, volume = asc.SimpleAudioVolume.MasterVolume, id = asc.GetID() }); }
public void TestforAdvert(Object stateInfo) { // Stop executing if Spotify was closed if (ToBreak()) { return; } spotifyControl = programGUI.getSpotify().QueryInterface <AudioSessionControl2>(); if (spotifyControl == null) { return; } // Make sure display is null programGUI.setDisplayVariable(null); // If an advert is playing if (spotifyControl.Process.MainWindowTitle.Equals("Advertisement") || spotifyControl.Process.MainWindowTitle.Equals("Spotify")) { spotifyVolume = spotifyControl.QueryInterface <SimpleAudioVolume>(); if (!spotifyVolume.IsMuted) { spotifyVolume.IsMuted = true; } if (!programGUI.getSongTitle().Equals(spotifyControl.Process.MainWindowTitle)) { programGUI.setSongTitle(spotifyControl.Process.MainWindowTitle); programGUI.setDisplayVariable("Advert detected..."); programGUI.playAudio(); } programGUI.setToPause(true); } }
private static List <VolumeObject> GetAllVolumeObjects() { List <VolumeObject> volumeObjects = new List <VolumeObject>(); // get the speakers (1st render + multimedia) device using (MMDeviceEnumerator deviceEnumerator = new MMDeviceEnumerator()) { // Find all the different "devices"/endpoints on PC using (var endpoints = deviceEnumerator.EnumAudioEndpoints(DataFlow.Render, DeviceState.Active)) { foreach (var endpoint in endpoints) { using (AudioSessionManager2 mgr = new AudioSessionManager2(endpoint.Activate(GUID_IAudioSessionManager2, CLSCTX.CLSCTX_ALL, IntPtr.Zero))) { using (var sessionEnumerator = mgr.GetSessionEnumerator()) { foreach (var session in sessionEnumerator) { // Note: This means audioSession must be disposed of AudioSessionControl2 audioSession = session.QueryInterface <AudioSessionControl2>(); volumeObjects.Add(new VolumeObject(audioSession.ProcessID, audioSession)); } } } } } } return(volumeObjects); }
public void HandleSessionCreated(object sender, CoreAudio.Interfaces.IAudioSessionControl2 newSession) { device.AudioSessionManager2.RefreshSessions(); AudioSessionControl2 sessionControl = new AudioSessionControl2(newSession); if (setAudioSessionEventHandlers(sessionControl)) { AudioSession createdSession = getAudioSessionObject(sessionControl); if (!AudioSessions.ContainsKey(createdSession.id)) { AudioSessions.Add(createdSession.id, createdSession); } else { AudioSessions[createdSession.id] = createdSession; } if (Main.LOG_EVENTS) { Console.WriteLine("\n New Session Created: " + createdSession.ToString()); } if (OnAudioSessionAdded != null) { OnAudioSessionAdded(createdSession); } } }
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; }
protected override void OnFormClosing(FormClosingEventArgs e) { audioSessionControl2 = null; if (hueUtil.isInit) { hueUtil.Stop(); } Thread.Sleep(500); }
public void Dispose() { _events.StateChanged -= OnStateChanged; _events.SimpleVolumeChanged -= OnVolumeChanged; Session.UnregisterAudioSessionNotification(_events); Session = null; _session2 = null; _simpleAudio = null; }
private void OnSessionCreated(object sender, CoreAudio.Interfaces.IAudioSessionControl2 newSession) { Dispatcher.Invoke(() => { SessionUI sessionUI = new SessionUI(); ConstructorInfo contructor = typeof(AudioSessionControl2).GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)[0]; AudioSessionControl2 session = contructor.Invoke(new object[] { newSession }) as AudioSessionControl2; sessionUI.SetSession(session); sessionControlStackPanel.Children.Add(sessionUI); }); }
private static void mute(AudioSessionControl2 session, bool notifiyUser = true) { var simpleAudioVolume = session.QueryInterface <SimpleAudioVolume>(); simpleAudioVolume.IsMuted = !simpleAudioVolume.IsMuted; if (notifiyUser) { OverlayHandler.Show(simpleAudioVolume.IsMuted ? "mute" : "loud"); } }
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); } }
public void TestforPaused(Object stateInfo) { spotifyControl = programGUI.getSpotify().QueryInterface <AudioSessionControl2>(); if (spotifyControl.Process.MainWindowTitle.Equals("Spotify Free")) { if (!programGUI.getSongTitle().Equals(spotifyControl.Process.MainWindowTitle) && !ToBreak()) { programGUI.setSongTitle(spotifyControl.Process.MainWindowTitle); programGUI.setDisplayVariable("Spotify is currently paused..."); } programGUI.setToPause(true); } }
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; } } }
public void HandleSessionDisconnected(object sender, CoreAudio.AudioSessionDisconnectReason reason) //NOT WORKING YET { AudioSessionControl2 sessionControl = (AudioSessionControl2)sender; AudioSession removedSession = getAudioSessionObject(sessionControl); if (Main.LOG_EVENTS) { Console.WriteLine("\nSession Removed:" + removedSession.ToString()); } if (OnAudioSessionRemoved != null) { OnAudioSessionRemoved(removedSession); } }
public void HandleIconPathChanged(object sender, string newItemPath) { AudioSessionControl2 senderSession = (AudioSessionControl2)sender; AudioSession changedSession = getAudioSessionObject(senderSession); if (Main.LOG_EVENTS) { Console.WriteLine("\nSession Volume Object icon path Changed: " + changedSession.ToString()); } if (OnAudioSessionIconChanged != null) { OnAudioSessionIconChanged(changedSession); } }
private void OnSessionCreated(object sender, CoreAudio.Interfaces.IAudioSessionControl2 newSession) { Dispatcher.Invoke(() => { SessionUI sessionUI = new SessionUI(); ConstructorInfo contructor = typeof(AudioSessionControl2).GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)[0]; AudioSessionControl2 session = contructor.Invoke(new object[] { newSession }) as AudioSessionControl2; sessionUI.SetSession(session); sessionStackPanel.Children.Add(sessionUI); this.sessions.Add(sessionUI); MainWindow.instance.SendAudioSession(sessions.IndexOf(sessionUI), session.SimpleAudioVolume.MasterVolume, session.SimpleAudioVolume.Mute, true); //Session_OnSimpleVolumeChanged(session, session.SimpleAudioVolume.MasterVolume, session.SimpleAudioVolume.Mute); SessionVolumeChanged(session, session.SimpleAudioVolume.MasterVolume, session.SimpleAudioVolume.Mute); //sessionUI.session.OnSimpleVolumeChanged += Session_OnSimpleVolumeChanged; }); }
public void Dispose() { _events.StateChanged -= OnStateChanged; _events.SimpleVolumeChanged -= OnVolumeChanged; _session?.UnregisterAudioSessionNotification(_events); _session?.Dispose(); _session = null; _session2?.Dispose(); _session2 = null; // Disposing of SimpleAudioVolume causes it to freeze. _simpleAudio = null; }
public void SessionVolumeChanged(object sender, float newVolume, bool newMute) { AudioSessionControl2 target = sender as AudioSessionControl2; int index = 0; foreach (SessionUI sessionUI in sessions) { if (sessionUI.session == target) { index = sessions.IndexOf(sessionUI); break; } } //Console.WriteLine($"Session {sessions[index].sessionLabel} vol: {newVolume} mute: {newMute}"); MainWindow.instance.SendAudioSession(index, newVolume, newMute); }
/// <summary> /// Subscribes audio Session to events /// </summary> /// <param name="sessionControl"></param> /// <returns>Returns false if the parent process of the audio session is dead</returns> private bool setAudioSessionEventHandlers(AudioSessionControl2 sessionControl) { bool sucess = true; Process sessionProcess; int pid = (int)sessionControl.GetProcessID; try { if (pid != 0 && AudioSessions.Values.FirstOrDefault(x => x.pid == pid) == null) { sessionProcess = Process.GetProcessById(pid); try { sessionProcess.EnableRaisingEvents = true; } catch (Win32Exception e) { //TODO: Find another way to detect wether a process is alive or not Console.WriteLine("Access for Process " + sessionProcess.ProcessName + " Denied :("); } sessionProcess.Exited += HandleProcessExited; } disconnectedDelegate = new AudioSessionControl2.SessionDisconnectedDelegate(HandleSessionDisconnected); displayNameChangedDelegate = new AudioSessionControl2.DisplayNameChangedDelegate(HandleDisplayNameChanged); iconPathChangedDelegate = new AudioSessionControl2.IconPathChangedDelegate(HandleIconPathChanged); volumeChangedDelegate = new AudioSessionControl2.SimpleVolumeChangedDelegate(HandleVolumeChanged); stateChangedDelegate = new AudioSessionControl2.StateChangedDelegate(Session_OnStateChanged); sessionControl.OnSessionDisconnected += disconnectedDelegate; // (object _sender, CoreAudio.AudioSessionDisconnectReason reason) => { HandleSessionDisconnected(_sender, reason); }; sessionControl.OnDisplayNameChanged += displayNameChangedDelegate; // (object _sender, string newName) => { HandleSessionChanged(_sender, AudioSessionChangedType.DisplayName); }; sessionControl.OnIconPathChanged += iconPathChangedDelegate; // (object _sender, string newItemPath) => { HandleIconPathChanged(_sender); }; sessionControl.OnSimpleVolumeChanged += volumeChangedDelegate; //(object _sender, float newVolume, bool newMute) => { HandleSessionChanged(_sender, AudioSessionChangedType.Volume); }; sessionControl.OnStateChanged += stateChangedDelegate; //Session_OnStateChanged; } catch (ArgumentException argex) {//Remove all Sessions which are of the dead process from AudioSessions sucess = false; string sessionID = sessionControl.GetID(); Console.WriteLine("\nProcess with ID " + pid + " dead, removing sessions of this process"); removeSessionsWithPid(pid); } return(sucess); }
public void FindSpotifyAdvertMuter(Object stateInfo) { Boolean found = false; // If we don't have Spotify if (programGUI.getSpotifyAdvertMuter() == null) { sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render); sessionEnumerator = sessionManager.GetSessionEnumerator(); Assert.IsNotNull(sessionEnumerator); foreach (AudioSessionControl session in sessionEnumerator) { if (session == null) { break; } sessionControl = session.QueryInterface <AudioSessionControl2>(); if (sessionControl == null) { break; } if (sessionControl.SessionIdentifier.Contains(System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName))) { spotifyAdvertMuterControl = sessionControl; programGUI.setSpotifyAdvertMuter(session); found = true; break; } } } if (found) { using var spotifyAdvertMuterVolume = spotifyAdvertMuterControl.QueryInterface <SimpleAudioVolume>(); spotifyAdvertMuterVolume.MasterVolume = 0.25f; } else { programGUI.setSpotifyAdvertMuter(null); spotifyAdvertMuterControl = null; } }
public List <string> GetSessionNames() { List <string> sessionNames = new List <string>(); foreach (AudioSessionControl session in audioSessionEnumerator) { AudioSessionControl2 sessionControl2 = session.QueryInterface <AudioSessionControl2>(); if (sessionControl2.DisplayName.ToLower().Contains("audiosrv.dll")) { sessionNames.Add("[System Sounds]"); } else { sessionNames.Add("[" + sessionControl2.Process.ProcessName + "] " + sessionControl2.Process.MainWindowTitle); } } return(sessionNames); }
public void FindSpotify(Object stateInfo) { Boolean found = false; // If we don't have Spotify if (programGUI.getSpotify() == null) { sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render); sessionEnumerator = sessionManager.GetSessionEnumerator(); Assert.IsNotNull(sessionEnumerator); foreach (AudioSessionControl session in sessionEnumerator) { if (session == null) { break; } sessionControl = session.QueryInterface <AudioSessionControl2>(); if (sessionControl == null) { break; } if (sessionControl.SessionIdentifier.Contains("Spotify.exe")) { spotifyControl = sessionControl; programGUI.setSpotify(session); found = true; break; } } } if (found) { programGUI.setDisplayBypass("Running..."); } else { programGUI.setSpotify(null); sessionControl = null; programGUI.setDisplayVariable(null); } }
private void FormMain_Load(object sender, EventArgs e) { labelHint.Text = "Initializing"; // init hueUtil hueUtil.Init(labelHint); // init audio Thread t = new Thread(() => { aps = AudioUtil.GetAudioApplications(); foreach (AudioApplication ap in aps) { RadioButton rb = new RadioButton { Text = ap.sessionName, Width = 280 }; rb.Click += (o, i) => { (new Thread(() => audioSessionControl2 = AudioUtil.GetAudioSessionControlByPid(ap.pid))).Start(); }; this.Invoke(new Action(() => { radioButtonslayout.Controls.Add(rb); })); } }); t.SetApartmentState(ApartmentState.MTA); t.Start(); // init timers timerPeak.Elapsed += Timer_GetPeakValue; timerPeak.Start(); timerGC.Elapsed += Timer_TrigerGC; timerGC.Start(); // trackbar saturation trackBarSaturation.Minimum = 0; trackBarSaturation.Maximum = 255; trackBarSaturation.Value = saturationValue; labelSaturation.Text = "Saturation: " + trackBarSaturation.Value; trackBarSaturation.ValueChanged += OnTrackBarSaturationChanged; }