internal void FireSessionCreated(IAudioSessionControl newSession) { if (this.OnSessionCreated != null) { this.OnSessionCreated(this, newSession); } }
private void CreateAndAddSession(IAudioSessionControl session) { try { if (!_parent.TryGetTarget(out IAudioDevice parent)) { throw new Exception("Device session parent is invalid but device is still notifying."); } var newSession = new AudioDeviceSession(parent, session); _dispatcher.BeginInvoke((Action)(() => { if (newSession.State == SessionState.Moved) { _movedSessions.Add(newSession); newSession.PropertyChanged += MovedSession_PropertyChanged; } else { AddSession(newSession); } })); } catch (ZombieProcessException ex) { // No need to log these to the cloud, but the debug output // can still be helpful for troubleshooting. Trace.TraceError($"{ex}"); } catch (Exception ex) { AppTrace.LogWarning(ex); } }
public AudioSession(IAudioSessionControl session) { _audioSessionControl = session; _simpleAudioVolume = session as ISimpleAudioVolume; _audioMeterInformation = session as IAudioMeterInformation; _audioSessionControl2 = session as IAudioSessionControl2; }
private void CreateAndAddSession(IAudioSessionControl session) { try { if (!_parent.TryGetTarget(out IAudioDevice parent)) { throw new Exception("Device session parent is invalid but device is still notifying."); } var newSession = new AudioDeviceSession(parent, session); _dispatcher.BeginInvoke((Action)(() => { if (newSession.State == SessionState.Moved) { _movedSessions.Add(newSession); newSession.PropertyChanged += MovedSession_PropertyChanged; } else { AddSession(newSession); } })); } catch (ZombieProcessException ex) { Trace.TraceError($"{ex}"); } catch (Exception ex) { Trace.TraceError($"{ex}"); } }
public ApplicationVolumeInformation(IAudioSessionControl Session, uint pProcessID, float pVolume, String pName, String pIconPath) { AudioSession = Session; ProcessID = pProcessID; _Volume = pVolume; Name = pName; IconPath = pIconPath; }
private async Task CreateSession(IAudioSessionControl sessionControl) { var managedSession = await ComThread.BeginInvoke(() => CacheSessionWrapper(sessionControl)).ConfigureAwait(false); if (managedSession != null) { OnSessionCreated(managedSession); } }
private static ImageSource ExtractSessionIcon(Process proc, IAudioSessionControl sc) { ImageSource icon = null; try { icon = IconHelper.GetFromProcess(proc); } catch (Win32Exception) { //"Win32Exception occurs when a 32-bit process is trying to access the modules of a 64-bit process" //occurs when the exe is a system process or it was launched via admin rights //it's possible to get system process icon from its IAudioSessionControl interface sc.GetIconPath(out var iconPath); if (string.IsNullOrEmpty(iconPath)) { //the icon path will be empty if the exe was launched with admin rights //looks like its impossible to get an icon of an exe with admin rights so we return generic windows exe icon return(IconHelper.GenericExeIcon); } try { //"The format of an icon resource specifier is "executable-file-path,resource-identifier" //where executable-file-path contains the fully qualified path of the file on a computer that contains the icon resource //and resource-identifier specifies an integer that identifies the resource." string[] resource = iconPath.Split(','); if (resource.Length < 2) { throw new Exception(); } //extract the icon from dll icon = IconHelper.GetFromDll(filePath: resource[0], resourceId: int.Parse(resource[1], CultureInfo.InvariantCulture)); } catch { } if (icon == null) { try { icon = IconHelper.GetFromFilePath(iconPath); } catch (Exception e) { Logger.Error($"Failed to extract session icon from the file path, process: [{proc.ProcessName}] file path: [{iconPath}]", e); } } } catch (Exception e) { Logger.Error($"Failed to extract icon from the process: [{proc.ProcessName}]", e); } return(icon ?? IconHelper.GenericExeIcon); }
public int OnSessionCreated(IAudioSessionControl newSession) { var session = newSession.GetAudioSessionModel(out bool isSystemSession); if (session != null) { this.SessionCreated?.Invoke(session); } return(0); }
private void OnSessionCreated(object sender, IAudioSessionControl newSession) { Console.WriteLine("OnSessionCreated"); midiDevice.LoadAssignments(); // These correspond with the below events handlers //NAudioEventCallbacks callbacks = new NAudioEventCallbacks(); //AudioSessionEventsCallback notifications = new AudioSessionEventsCallback(callbacks); //audioSession.RegisterEventClient(callbacks); }
// Lists all devices, and for each device all processes that are currently playing sound using that device public static List <SoundInfoDevice> getSoundInfo() { List <SoundInfoDevice> soundInfoDevices = new List <SoundInfoDevice>(); DeviceEnumerator enumerator = new DeviceEnumerator(); IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)enumerator; IMMDeviceCollection deviceCollection = deviceEnumerator.EnumAudioEndpoints(EDataFlow.eRender, DeviceStatemask.DEVICE_STATE_ACTIVE); uint deviceCount = deviceCollection.GetCount(); for (uint i = 0; i < deviceCount; i++) { SoundInfoDevice soundInfoDevice = new SoundInfoDevice(); soundInfoDevices.Add(soundInfoDevice); IMMDevice device = deviceCollection.Item(i); string deviceId = device.GetId(); soundInfoDevice.ID = deviceId; IMMPropertyStore propertyStore = device.OpenPropertyStore(ProperyStoreMode.STGM_READ); PropertyKey propertyKeyDeviceDesc = new PropertyKey(); propertyKeyDeviceDesc.fmtid = new Guid(0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0); propertyKeyDeviceDesc.pid = 2; PropVariant deviceNamePtr = propertyStore.GetValue(ref propertyKeyDeviceDesc); string deviceName = Marshal.PtrToStringUni(deviceNamePtr.pszVal); soundInfoDevice.name = deviceName; Guid guidAudioSessionManager2 = new Guid("77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F"); IAudioSessionManager2 audioSessionManager = (IAudioSessionManager2)device.Activate(ref guidAudioSessionManager2, (int)ClsCtx.CLSCTX_ALL, IntPtr.Zero); IAudioSessionEnumerator sessionEnumerator = audioSessionManager.GetSessionEnumerator(); int sessionCount = sessionEnumerator.GetCount(); for (int j = 0; j < sessionCount; j++) { IAudioSessionControl audioSessionControl = sessionEnumerator.GetSession(j); IAudioSessionControl2 audioSessionControl2 = (IAudioSessionControl2)audioSessionControl; AudioSessionState state = audioSessionControl.GetState(); if (state == AudioSessionState.AudioSessionStateActive) { SoundInfoSession soundInfoSession = new SoundInfoSession(); soundInfoDevice.sessions.Add(soundInfoSession); string displayName = audioSessionControl.GetDisplayName(); string iconPath = audioSessionControl.GetIconPath(); int processId = audioSessionControl2.GetProcessId(); string processName = Process.GetProcessById(processId).MainWindowTitle; soundInfoSession.pid = processId; soundInfoSession.windowName = processName; } } } return(soundInfoDevices); }
void sessionCreatedNotificaton(object sender, IAudioSessionControl newSession) { try { this.Invoke(new Action(delegate() { device.AudioSessionManager.RefreshSessions(); updateSessions(); })); } catch { } }
/// <summary> /// Constructor. /// </summary> /// <param name="audioSessionControl"></param> public AudioSessionControl(IAudioSessionControl audioSessionControl) { audioSessionControlInterface = audioSessionControl; audioSessionControlInterface2 = audioSessionControl as IAudioSessionControl2; var meters = audioSessionControlInterface as IAudioMeterInformation; var volume = audioSessionControlInterface as ISimpleAudioVolume; if (meters != null) audioMeterInformation = new AudioMeterInformation(meters); if (volume != null) simpleAudioVolume = new SimpleAudioVolume(volume); }
// getting IAudioSessionControl2 out of IAudioSessionControl via QueryInterface private static IAudioSessionControl2 GetAudioControl2(IAudioSessionControl ctl) { IntPtr pUnk = Marshal.GetIUnknownForObject(ctl); IntPtr pI; Guid baseGuid = typeof(IAudioSessionControl).GUID; Marshal.QueryInterface(pUnk, ref baseGuid, out pI); object asc = Marshal.GetObjectForIUnknown(pI); IAudioSessionControl2 asc2 = (IAudioSessionControl2)asc; return(asc2); }
private void AddNewSession(IAudioSessionControl iasc) { var asc = iasc as AudioSessionControl; L.SNames.Add(asc.DisplayName); //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}"); }
public AudioSessionControl(IAudioSessionControl audioSessionControl) { _audioSessionControl = audioSessionControl; _audioSessionControl2 = audioSessionControl as IAudioSessionControl2; //if (_audioSessionControl2 == null) // throw new InvalidOperationException("Not supported on this version of Windows"); if (_audioSessionControl is ISimpleAudioVolume simpleVolume) { _simpleAudioVolume = new SimpleAudioVolume(simpleVolume); } }
internal AudioSessionControl(IAudioSessionControl realAudioSessionControl) { IAudioMeterInformation _meters = realAudioSessionControl as IAudioMeterInformation; ISimpleAudioVolume _volume = realAudioSessionControl as ISimpleAudioVolume; if (_meters != null) _AudioMeterInformation = new CoreAudio.AudioMeterInformation(_meters); if (_volume != null) _SimpleAudioVolume = new SimpleAudioVolume(_volume); _AudioSessionControl = realAudioSessionControl; _AudioSessionEvents = new AudioSessionEvents(this); Marshal.ThrowExceptionForHR(_AudioSessionControl.RegisterAudioSessionNotification(_AudioSessionEvents)); }
/// <summary> /// Constructor. /// </summary> /// <param name="audioSessionControl"></param> public AudioSessionControl(IAudioSessionControl audioSessionControl) { audioSessionControlInterface = audioSessionControl; audioSessionControlInterface2 = audioSessionControl as IAudioSessionControl2; if (audioSessionControlInterface is IAudioMeterInformation meters) { AudioMeterInformation = new AudioMeterInformation(meters); } if (audioSessionControlInterface is ISimpleAudioVolume volume) { SimpleAudioVolume = new SimpleAudioVolume(volume); } }
private CoreAudioSession CacheSessionWrapper(IAudioSessionControl session) { var managedSession = new CoreAudioSession(_device, session); //There's some dumb crap in the Api that causes the sessions to still appear //even after the process has been terminated if (Process.GetProcesses().All(x => x.Id != managedSession.ProcessId)) { return(null); } var acquiredLock = _lock.AcquireReadLockNonReEntrant(); try { var existing = _sessionCache.FirstOrDefault(x => x.ProcessId == managedSession.ProcessId && String.Equals(x.Id, managedSession.Id)); if (existing != null) { managedSession.Dispose(); return(existing); } } finally { if (acquiredLock) { _lock.ExitReadLock(); } } managedSession.StateChanged.Subscribe(ManagedSessionOnStateChanged); managedSession.Disconnected.Subscribe(ManagedSessionOnDisconnected); acquiredLock = _lock.AcquireWriteLockNonReEntrant(); try { _sessionCache.Add(managedSession); } finally { if (acquiredLock) { _lock.ExitWriteLock(); } } return(managedSession); }
public AudioSessionControl(IAudioSessionControl audioSessionControl) { this.audioSessionControlInterface = audioSessionControl; this.audioSessionControlInterface2 = (audioSessionControl as IAudioSessionControl2); IAudioMeterInformation audioMeterInformation = this.audioSessionControlInterface as IAudioMeterInformation; ISimpleAudioVolume simpleAudioVolume = this.audioSessionControlInterface as ISimpleAudioVolume; if (audioMeterInformation != null) { this.audioMeterInformation = new AudioMeterInformation(audioMeterInformation); } if (simpleAudioVolume != null) { this.simpleAudioVolume = new SimpleAudioVolume(simpleAudioVolume); } }
public AudioSessionControl FindSession(IAudioSessionManager2 session_manager, AudioSessionProc matchsession_proc, object data) { AudioSessionControl res = null; IAudioSessionEnumerator sessionList = null; session_manager.GetSessionEnumerator(out sessionList); if (sessionList == null) { return(null); } int cnt = 0; sessionList.GetCount(out cnt); for (int index = 0; index < cnt; index++) { IAudioSessionControl session = null; sessionList.GetSession(index, out session); if (session == null) { continue; } bool quit = false; AudioSessionControl control = null; try { control = new AudioSessionControl(session); quit = (matchsession_proc(control, data) == false); if (quit) { res = control; break; } control.Dispose(); Marshal.Release(Marshal.GetIUnknownForObject(session)); } catch { } { } } Marshal.Release(Marshal.GetIUnknownForObject(sessionList)); GC.WaitForPendingFinalizers(); return(res); }
/// <summary> /// Constructor. /// </summary> /// <param name="audioSessionControl"></param> public AudioSessionControl(IAudioSessionControl audioSessionControl) { audioSessionControlInterface = audioSessionControl; audioSessionControlInterface2 = audioSessionControl as IAudioSessionControl2; var meters = audioSessionControlInterface as IAudioMeterInformation; var volume = audioSessionControlInterface as ISimpleAudioVolume; if (meters != null) { audioMeterInformation = new AudioMeterInformation(meters); } if (volume != null) { simpleAudioVolume = new SimpleAudioVolume(volume); } }
internal AudioSessionControl(IAudioSessionControl realAudioSessionControl) { IAudioMeterInformation _meters = realAudioSessionControl as IAudioMeterInformation; ISimpleAudioVolume _volume = realAudioSessionControl as ISimpleAudioVolume; if (_meters != null) { _AudioMeterInformation = new CoreAudio.AudioMeterInformation(_meters); } if (_volume != null) { _SimpleAudioVolume = new SimpleAudioVolume(_volume); } _AudioSessionControl = realAudioSessionControl; //_AudioSessionEvents = new AudioSessionEvents(this); Marshal.ThrowExceptionForHR(_AudioSessionControl.RegisterAudioSessionNotification(_AudioSessionEvents)); }
/// <summary> /// Constructor. /// </summary> /// <param name="audioSessionControl"></param> public AudioSessionControl(IAudioSessionControl audioSessionControl) { audioSessionControlInterface = audioSessionControl; audioSessionControlInterface2 = audioSessionControl as IAudioSessionControl2; // ReSharper disable once SuspiciousTypeConversion.Global var meters = audioSessionControlInterface as IAudioMeterInformation; // ReSharper disable once SuspiciousTypeConversion.Global var volume = audioSessionControlInterface as ISimpleAudioVolume; if (meters != null) { AudioMeterInformation = new AudioMeterInformation(meters); } if (volume != null) { SimpleAudioVolume = new SimpleAudioVolume(volume); } }
private bool sessionIsActive(IAudioSessionEnumerator sessionEnumerator, int sessionIndex) { IAudioSessionControl sessionControl = null; try { sessionEnumerator.GetSession(sessionIndex, out sessionControl); AudioSessionState sessionState = AudioSessionState.AudioSessionStateInactive; sessionControl.GetState(out sessionState); return(sessionState == AudioSessionState.AudioSessionStateActive); } finally { if (sessionControl != null) { Marshal.ReleaseComObject(sessionControl); } } }
private static string GetSystemSoundsName(this IAudioSessionControl sc) { string systemSoundsName = string.Empty; string resourcePath = string.Empty; try { sc.GetDisplayName(out resourcePath); if (!string.IsNullOrEmpty(resourcePath)) { var index = int.Parse(resourcePath.Split(',')[1], CultureInfo.InvariantCulture); systemSoundsName = NativeMethods.ExtractStringFromSystemDLL("AudioSrv.dll", index < 0 ? -index : index); } } catch (Exception e) { Logger.Error($"Failed to get system sounds session name, path: [{resourcePath}]", e); } return(systemSoundsName); }
public CoreAudioSession(CoreAudioDevice device, IAudioSessionControl control) { ComThread.Assert(); // ReSharper disable once SuspiciousTypeConversion.Global var audioSessionControl = control as IAudioSessionControl2; // ReSharper disable once SuspiciousTypeConversion.Global var simpleAudioVolume = control as ISimpleAudioVolume; if (audioSessionControl == null || simpleAudioVolume == null) { throw new InvalidComObjectException("control"); } _controlPtr = Marshal.GetIUnknownForObject(control); _audioSessionControl = new ThreadLocal <IAudioSessionControl2>(() => Marshal.GetUniqueObjectForIUnknown(_controlPtr) as IAudioSessionControl2); _meterInformation = new ThreadLocal <IAudioMeterInformation>(() => Marshal.GetUniqueObjectForIUnknown(_controlPtr) as IAudioMeterInformation); _simpleAudioVolume = new ThreadLocal <ISimpleAudioVolume>(() => Marshal.GetUniqueObjectForIUnknown(_controlPtr) as ISimpleAudioVolume); Device = device; _deviceMutedSubscription = Device.MuteChanged.Subscribe(x => { OnMuteChanged(_isMuted); }); _stateChanged = new Broadcaster <SessionStateChangedArgs>(); _disconnected = new Broadcaster <SessionDisconnectedArgs>(); _volumeChanged = new Broadcaster <SessionVolumeChangedArgs>(); _muteChanged = new Broadcaster <SessionMuteChangedArgs>(); _peakValueChanged = new Broadcaster <SessionPeakValueChangedArgs>(); AudioSessionControl.RegisterAudioSessionNotification(this); RefreshProperties(); RefreshVolume(); }
internal AudioSessionControl(IAudioSessionControl audioSessionControl) { audioSessionControlInterface = audioSessionControl; }
/// <summary> /// Finds the matching process and volume control /// </summary> /// <param name="processName">The name of the process to find</param> /// <param name="selectedProcess">The selected process</param> /// <param name="volumeControl">The volume control object</param> private static void FindMatchingProcess(string processName, out Process selectedProcess, out ISimpleAudioVolume volumeControl) { selectedProcess = null; volumeControl = null; // First find the list of matching processes Process[] matchingProcesses = Process.GetProcessesByName(processName); if (matchingProcesses != null && matchingProcesses.Length > 0) { // Attempt to see if we can find an audio session with the same Process ID as one we have found IMMDeviceEnumerator deviceEnumerator = null; IMMDevice device = null; IAudioSessionManager2 sessionManager = null; IAudioSessionEnumerator sessionEnumerator = null; object activatedObject = null; Guid sessionManagerGuid = typeof(IAudioSessionManager2).GUID; try { // Create the Device Enumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator()); // Get the default audio device if (deviceEnumerator != null) { deviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia, out device); } // Get the Session Manager if (device != null) { device.Activate(ref sessionManagerGuid, (uint)0, IntPtr.Zero, out activatedObject); sessionManager = activatedObject as IAudioSessionManager2; activatedObject = null; } // Get the Session Enumerator if (sessionManager != null) { sessionManager.GetSessionEnumerator(out sessionEnumerator); } // Look through the list of Sessions and find one with a matching process ID. if (sessionEnumerator != null) { int totalSessions = 0; sessionEnumerator.GetCount(out totalSessions); for (int currentSession = 0; currentSession < totalSessions; currentSession++) { IAudioSessionControl currentSessionControl = null; sessionEnumerator.GetSession(currentSession, out currentSessionControl); IAudioSessionControl2 currentSessionControl2 = currentSessionControl as IAudioSessionControl2; if (currentSessionControl2 != null) { uint processID = 0; currentSessionControl2.GetProcessID(out processID); foreach (Process currentProcess in matchingProcesses) { // We found the correct process and audio session if (currentProcess.Id == processID) { selectedProcess = currentProcess; volumeControl = currentSessionControl as ISimpleAudioVolume; break; } } } if (selectedProcess != null) { // We found the volume control break; } else { // Free the current session Marshal.ReleaseComObject(currentSessionControl); } } } } finally { // Clean up the COM Objects that we used if (activatedObject != null) { Marshal.ReleaseComObject(activatedObject); } if (sessionEnumerator != null) { Marshal.ReleaseComObject(sessionEnumerator); } if (sessionManager != null) { Marshal.ReleaseComObject(sessionManager); } if (device != null) { Marshal.ReleaseComObject(device); } if (deviceEnumerator != null) { Marshal.ReleaseComObject(deviceEnumerator); } } // If we get here for some reason and don't have a matching process then we will just take the first one with a valid Window Handle if (selectedProcess == null) { foreach (Process currentProcess in matchingProcesses) { if (currentProcess != null && currentProcess.MainWindowHandle != IntPtr.Zero) { selectedProcess = currentProcess; break; } } } } }
public int OnSessionCreated(IAudioSessionControl newSession) { parent.FireSessionCreated(newSession); return 0; }
internal void FireSessionCreated(IAudioSessionControl newSession) { OnSessionCreated?.Invoke(this, newSession); }
public static IEnumerable <ApplicationVolumeInformation> EnumerateApplications() { // get the speakers (1st render + multimedia) device IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator()); IMMDevice speakers; deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers); // activate the session manager. we need the enumerator Guid IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID; object o; speakers.Activate(IID_IAudioSessionManager2, 0, IntPtr.Zero, out o); IAudioSessionManager2 mgr = (IAudioSessionManager2)o; // enumerate sessions for on this device IAudioSessionEnumerator sessionEnumerator; mgr.GetSessionEnumerator(out sessionEnumerator); int count; sessionEnumerator.GetCount(out count); for (int i = 0; i < count; i++) { IAudioSessionControl ctl; sessionEnumerator.GetSession(i, out ctl); uint GetProcessID = 0; String GetName = ""; float GetVolume = 0; String GetIconPath = ""; IAudioSessionControl getsession = null; getsession = ctl; if (ctl is IAudioSessionControl2) { IAudioSessionControl2 ctl2 = ((IAudioSessionControl2)ctl); ctl2.GetProcessId(out GetProcessID); ctl2.GetDisplayName(out GetName); String sIconPath; ctl2.GetIconPath(out sIconPath); ISimpleAudioVolume volcast = (ctl2 as ISimpleAudioVolume); float grabvolume; volcast.GetMasterVolume(out grabvolume); GetVolume = grabvolume; try { Process grabProcess = Process.GetProcessById((int)GetProcessID); if (String.IsNullOrEmpty(GetName)) { GetName = grabProcess.ProcessName; } } catch (Exception exx) { GetName = "Name Not Available"; } } ApplicationVolumeInformation avi = new ApplicationVolumeInformation(getsession, GetProcessID, GetVolume, GetName, GetIconPath); yield return(avi); Marshal.ReleaseComObject(ctl); } Marshal.ReleaseComObject(sessionEnumerator); Marshal.ReleaseComObject(mgr); Marshal.ReleaseComObject(speakers); Marshal.ReleaseComObject(deviceEnumerator); }
internal void FireSessionCreated(IAudioSessionControl newSession) { if (OnSessionCreated != null) OnSessionCreated(this, newSession); }
public int OnSessionCreated(IAudioSessionControl newSession) { parent.FireSessionCreated(newSession); return(0); }
void IAudioSessionNotification.OnSessionCreated(IAudioSessionControl NewSession) { Trace.WriteLine($"AudioDeviceSessionCollection OnSessionCreated"); CreateAndAddSession(NewSession); }
private void AudioSessionManager_OnSessionCreated(object sender, IAudioSessionControl newSession) { var audioSessionControl = new AudioSessionControl(newSession); if (_audioSessionControl == null && audioSessionControl.GetProcessID == Process.GetCurrentProcess().Id) { _audioSessionControl = audioSessionControl; _audioSessionControl.RegisterEventClient(this); if (_audioSessionControl.SimpleAudioVolume.Mute) { _isMuted = true; } UpdateVolume(); UpdateIsMuted(); } }
public ApplicationVolumeInformation(IAudioSessionControl Session,uint pProcessID,float pVolume,String pName,String pIconPath) { AudioSession = Session; ProcessID = pProcessID; _Volume = pVolume; Name = pName; IconPath = pIconPath; }
public Audio() { this.AudioVolume = null; var deviceEnumeratorType = Type.GetTypeFromCLSID(new Guid(ComCLSIDs.MMDeviceEnumeratorCLSID)); var devenum = (IMMDeviceEnumerator)Activator.CreateInstance(deviceEnumeratorType); IMMDevice device = null; if (devenum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out device) == 0) { var iid = new Guid(ComIIDs.IAudioSessionManager2IID); object objAudioSessionManager = null; if (device.Activate(iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, IntPtr.Zero, out objAudioSessionManager) == 0) { var AudioSessionManager = objAudioSessionManager as IAudioSessionManager2; ISimpleAudioVolume AudioVolume; if (AudioSessionManager.GetSimpleAudioVolume(Guid.Empty, 0, out AudioVolume) == 0) { this.AudioVolume = AudioVolume; } IAudioSessionControl AudioControl; if (AudioSessionManager.GetAudioSessionControl(Guid.Empty, 0, out AudioControl) == 0) { this.AudioControl = AudioControl; this.AudioControl.RegisterAudioSessionNotification(this); } } } }