public AEDev() { IMMDevice _Device = null; if (String.IsNullOrEmpty(_devId)) { Marshal.ThrowExceptionForHR(_realEnumerator.GetDefaultAudioEndpoint(0, 1, out _Device)); Marshal.ThrowExceptionForHR(_Device.GetId(out _devId)); } else { Marshal.ThrowExceptionForHR(_realEnumerator.GetDevice(_devId, out _Device)); } devstatus state; Marshal.ThrowExceptionForHR(_Device.GetState(out state)); if (state != devstatus.DEVICE_STATE_ACTIVE) throw new ApplicationException(String.Format("audio device is not active ({0})", state.ToString())); _RealDevice = _Device; object result; Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioEndpointVolume, CTX.ALL, IntPtr.Zero, out result)); _AudioEndPointVolume = result as IAudioEndpointVolume; _CallBack = new AudioEndpointVolumeCallback(this); Marshal.ThrowExceptionForHR(_AudioEndPointVolume.RegisterControlChangeNotify(_CallBack)); }
public AudioDeviceSessionCollection(IAudioDevice parent, IMMDevice device) { Trace.WriteLine($"AudioDeviceSessionCollection Create dev={device.GetId()}"); _parent = new WeakReference <IAudioDevice>(parent); _dispatcher = App.Current.Dispatcher; Task.Factory.StartNew(() => { try { _sessionManager = device.Activate <IAudioSessionManager2>(); _sessionManager.RegisterSessionNotification(this); var enumerator = _sessionManager.GetSessionEnumerator(); int count = enumerator.GetCount(); for (int i = 0; i < count; i++) { CreateAndAddSession(enumerator.GetSession(i)); } } catch (Exception ex) { Trace.TraceError($"{ex}"); } }); }
private static ISimpleAudioVolume GetAudioVolume(int pid) { IMMDevice device = GetDefaultDevice(); Guid IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID; device.Activate(ref IID_IAudioSessionManager2, 0, IntPtr.Zero, out var result); IAudioSessionManager2 sessionManager = (IAudioSessionManager2)result; sessionManager.GetSessionEnumerator(out var sessionEnumerator); sessionEnumerator.GetCount(out var count); ISimpleAudioVolume volumeControl = null; for (int i = 0; i < count; i++) { sessionEnumerator.GetSession(i, out var sessionControl2); sessionControl2.GetProcessId(out var processId); if (processId == pid) { volumeControl = sessionControl2 as ISimpleAudioVolume; break; } Marshal.ReleaseComObject(sessionControl2); } Marshal.ReleaseComObject(sessionEnumerator); Marshal.ReleaseComObject(sessionManager); Marshal.ReleaseComObject(device); return(volumeControl); }
public MMDevice GetDevice(string ID) { IMMDevice _Device = null; Marshal.ThrowExceptionForHR(((IMMDeviceEnumerator)_realEnumerator).GetDevice(ID, out _Device)); return(new MMDevice(_Device)); }
public string GetDeviceId(IMMDevice device) { string device_id = ""; device.GetId(out device_id); return(device_id); }
/// <summary> /// Gets a list of available audio capture devices. /// </summary> /// <returns> /// An array of available capture device names. /// </returns> public static string[] GetAvailableCaptureDevices() { // Get the collection of available capture devices IMMDeviceCollection deviceCollection = DeviceUtil.GetAvailableDevices(EDataFlow.Capture); string[] devices = null; int deviceCount = deviceCollection.GetCount(); devices = new string[deviceCount]; // Iterate over the collection to get the device names for (int i = 0; i < deviceCount; i++) { IMMDevice device = deviceCollection.Item(i); // Get the friendly name of the device devices[i] = DeviceUtil.GetDeviceFriendlyName(device); // Done with the device so release it Marshal.ReleaseComObject(device); } // Release the collection when done Marshal.ReleaseComObject(deviceCollection); return(devices); }
/// <summary> /// Initializes the audio capture device. /// </summary> /// <param name="deviceDescription"> /// The friendly name description of the device to capture from. This is usually /// something like "Microphone Array (USB Audio)". To capture from /// the default device, pass in NULL or an empty string. /// </param> public void Initialize(string deviceDescription) { // Activate native audio COM objects on a thread-pool thread to ensure that they are in an MTA Task.Run(() => { if (string.IsNullOrEmpty(deviceDescription)) { // use the default console device this.audioDevice = DeviceUtil.GetDefaultDevice(EDataFlow.Capture, ERole.Console); } else { this.audioDevice = DeviceUtil.GetDeviceByName(EDataFlow.Capture, deviceDescription); } if (this.audioDevice != null) { // Try to get the volume control object obj = this.audioDevice.Activate(new Guid(Guids.IAudioEndpointVolumeIIDString), ClsCtx.ALL, IntPtr.Zero); this.volume = (IAudioEndpointVolume)obj; // Now create an IAudioEndpointVolumeCallback object that wraps the callback and register it with the endpoint. this.volumeCallback = new AudioEndpointVolumeCallback(this.AudioVolumeCallback); this.volume.RegisterControlChangeNotify(this.volumeCallback); } }).Wait(); }
/// <summary> /// Get device by ID /// </summary> /// <param name="id">Device ID</param> /// <returns>Device</returns> public MMDevice GetDevice(string id) { IMMDevice device = null; Marshal.ThrowExceptionForHR(((IMMDeviceEnumerator)realEnumerator).GetDevice(id, out device)); return(new MMDevice(device)); }
internal static string GetID(IMMDevice realDevice) { string result; Marshal.ThrowExceptionForHR(realDevice.GetId(out result)); return(result); }
/// <summary> /// The Initialize Audio Controls /// </summary> public void InitializeAudioControls(AudioDataFlow initFlow, string pid, string vid) { IMMDevice _audioDevice = null; //Get Audio Device switch (initFlow) { case AudioDataFlow.eAll: _audioDevice = GetIMMDevice(AudioDataFlow.eRender, pid, vid); _speakerControl = new AudioControl(_audioDevice, AudioDataFlow.eRender); _audioSessionControl = new AudioSessionControl(_audioDevice, AudioDataFlow.eRender); _audioDevice = GetIMMDevice(AudioDataFlow.eCapture, pid, vid); _microphoneControl = new AudioControl(_audioDevice, AudioDataFlow.eCapture); break; case AudioDataFlow.eRender: _audioDevice = GetIMMDevice(initFlow, pid, vid); _speakerControl = new AudioControl(_audioDevice, initFlow); break; case AudioDataFlow.eCapture: _audioDevice = GetIMMDevice(initFlow, pid, vid); _microphoneControl = new AudioControl(_audioDevice, initFlow); break; } }
private string GetAudioDeviceName(ref IMMDevice audioDevice) { IPropertyStore propertyStore; Marshal.ThrowExceptionForHR(audioDevice.OpenPropertyStore(StorageAccessMode.Read, out propertyStore)); int numProperties; Marshal.ThrowExceptionForHR(propertyStore.GetCount(out numProperties)); string deviceName = String.Empty; for (int propertyNum = 0; propertyNum < numProperties; ++propertyNum) { PropertyKey propertyKey; Marshal.ThrowExceptionForHR(propertyStore.GetAt(propertyNum, out propertyKey)); if ((propertyKey.formatId == PKEY_Device_FriendlyName.formatId) && (propertyKey.propertyId == PKEY_Device_FriendlyName.propertyId)) { PropVariant propertyValue; Marshal.ThrowExceptionForHR(propertyStore.GetValue(ref propertyKey, out propertyValue)); deviceName = Marshal.PtrToStringUni(propertyValue.pointerValue); break; } } Marshal.ReleaseComObject(propertyStore); return(deviceName); }
public static IAudioEndpointVolume GetMasterVolumeHandler() { IMMDeviceEnumerator deviceEnumerator = null; IMMDevice speakers = null; try { deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator()); deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers); var audioEndpointVolume = typeof(IAudioEndpointVolume).GUID; speakers.Activate(ref audioEndpointVolume, 0, IntPtr.Zero, out object masterVolume); return((IAudioEndpointVolume)masterVolume); } finally { if (speakers != null) { Marshal.ReleaseComObject(speakers); } if (deviceEnumerator != null) { Marshal.ReleaseComObject(deviceEnumerator); } } }
private static ISimpleAudioVolume GetVolumeObject(string name) { IMMDeviceEnumerator devices = (IMMDeviceEnumerator) new MMDeviceEnumerator(); IMMDevice device = devices.GetDefaultAudioEndpoint(EDATAFLOW_RENDER, EROLE_MULTIMEDIA); Guid sessionManagerGUID = typeof(IAudioSessionManager2).GUID; IAudioSessionManager2 manager = (IAudioSessionManager2)device.Activate(ref sessionManagerGUID, 0, IntPtr.Zero); IAudioSessionEnumerator sessions = manager.GetSessionEnumerator(); ISimpleAudioVolume volumeObj = null; for (int index = sessions.GetCount() - 1; index >= 0; index--) { IAudioSessionControl2 ctl = sessions.GetSession(index) as IAudioSessionControl2; if (ctl != null) { string identifier = ctl.GetSessionIdentifier(); if (identifier != null && identifier.Contains(name)) { volumeObj = ctl as ISimpleAudioVolume; break; } Marshal.ReleaseComObject(ctl); } } Marshal.ReleaseComObject(devices); Marshal.ReleaseComObject(device); Marshal.ReleaseComObject(manager); Marshal.ReleaseComObject(sessions); return(volumeObj); }
internal CoreAudioDevice(IMMDevice device, IAudioController <CoreAudioDevice> controller) : base(controller) { _device = device; ComThread.Assert(); if (device == null) { throw new ArgumentNullException("device"); } LoadProperties(device); GetAudioMeterInformation(device); GetAudioEndpointVolume(device); if (AudioEndpointVolume != null) { AudioEndpointVolume.OnVolumeNotification += AudioEndpointVolume_OnVolumeNotification; } controller.AudioDeviceChanged += new EventHandler <AudioDeviceChangedEventArgs>(EnumeratorOnAudioDeviceChanged) .MakeWeak(x => { controller.AudioDeviceChanged -= x; }); }
public AEDev() { IMMDevice _Device = null; if (String.IsNullOrEmpty(_devId)) { Marshal.ThrowExceptionForHR(_realEnumerator.GetDefaultAudioEndpoint(0, 1, out _Device)); Marshal.ThrowExceptionForHR(_Device.GetId(out _devId)); } else { Marshal.ThrowExceptionForHR(_realEnumerator.GetDevice(_devId, out _Device)); } devstatus state; Marshal.ThrowExceptionForHR(_Device.GetState(out state)); if (state != devstatus.DEVICE_STATE_ACTIVE) { throw new ApplicationException(String.Format("audio device is not active ({0})", state.ToString())); } _RealDevice = _Device; object result; Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioEndpointVolume, CTX.ALL, IntPtr.Zero, out result)); _AudioEndPointVolume = result as IAudioEndpointVolume; _CallBack = new AudioEndpointVolumeCallback(this); Marshal.ThrowExceptionForHR(_AudioEndPointVolume.RegisterControlChangeNotify(_CallBack)); }
public static T Activate <T>(this IMMDevice device) { Guid iid = typeof(T).GUID; device.Activate(ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, IntPtr.Zero, out object ret); return((T)ret); }
public void IMMDeviceEnumerator_GetDevice() { int result = 0; var enumerator = TestUtilities.CreateIMMDeviceEnumerator(); var allDevices = TestUtilities.CreateIMMDeviceCollection(EDataFlow.eAll, DEVICE_STATE_XXX.DEVICE_STATEMASK_ALL); foreach (var device in allDevices) { // Get the device ID. string deviceId = null; result = device.GetId(out deviceId); AssertCoreAudio.IsHResultOk(result); Assert.IsNotNull(deviceId, "The device string is null."); // Get the IMMDevice directly from the ID. IMMDevice deviceFromId = null; result = enumerator.GetDevice(deviceId, out deviceFromId); AssertCoreAudio.IsHResultOk(result); Assert.IsNotNull(deviceFromId, "The IMMDevice object is null."); // Ensure the IDs of each device match. string deviceId2 = null; result = deviceFromId.GetId(out deviceId2); AssertCoreAudio.IsHResultOk(result); Assert.IsNotNull(deviceId2, "The device string is null."); Assert.AreEqual(deviceId, deviceId2, "The device IDs are not equal."); } }
private static ISimpleAudioVolume GetVolumeObject(int pid, IMMDevice device) { // Activate the session manager. we need the enumerator Guid iidIAudioSessionManager2 = typeof(IAudioSessionManager2).GUID; device.Activate(ref iidIAudioSessionManager2, 0, IntPtr.Zero, out object o); IAudioSessionManager2 mgr = (IAudioSessionManager2)o; // Enumerate sessions for this device mgr.GetSessionEnumerator(out IAudioSessionEnumerator sessionEnumerator); sessionEnumerator.GetCount(out int count); // Search for an audio session with the required name // NOTE: we could also use the process id instead of the app name (with IAudioSessionControl2) ISimpleAudioVolume volumeControl = null; for (int i = 0; i < count; i++) { sessionEnumerator.GetSession(i, out IAudioSessionControl2 ctl); ctl.GetProcessId(out int cpid); if (cpid == pid) { // ReSharper disable once SuspiciousTypeConversion.Global volumeControl = (ISimpleAudioVolume)ctl; break; } Marshal.ReleaseComObject(ctl); } Marshal.ReleaseComObject(sessionEnumerator); Marshal.ReleaseComObject(mgr); return(volumeControl); }
private static IAudioEndpointVolume GetMasterVolumeObject() { IMMDeviceEnumerator deviceEnumerator = null; IMMDevice speakers = null; try { deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator()); deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers); Guid IID_IAudioEndpointVolume = typeof(IAudioEndpointVolume).GUID; object o; if (speakers == null) { return(null); } speakers.Activate(ref IID_IAudioEndpointVolume, 0, IntPtr.Zero, out o); IAudioEndpointVolume masterVol = (IAudioEndpointVolume)o; return(masterVol); } finally { if (speakers != null) { Marshal.ReleaseComObject(speakers); } if (deviceEnumerator != null) { Marshal.ReleaseComObject(deviceEnumerator); } } }
/// <summary> /// 指示系统当前是否在播放声音 /// </summary> /// <returns></returns> public static bool IsWindowsPlayingSound() { try { IMMDeviceEnumerator enumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator()); IMMDevice speakers = enumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia); IAudioMeterInformation meter = (IAudioMeterInformation)speakers.Activate(typeof(IAudioMeterInformation).GUID, 0, IntPtr.Zero); if (meter != null) { float value = meter.GetPeakValue(); // this is a bit tricky. 0 is the official "no sound" value // but for example, if you open a video and plays/stops with it (w/o killing the app/window/stream), // the value will not be zero, but something really small (around 1E-09) // so, depending on your context, it is up to you to decide // if you want to test for 0 or for a small value return(value > 1E-08); } else { return(false); } } catch (Exception ec) { LogHelper.Warning(ec.ToString()); return(false); } }
public AudioDevice(IAudioDeviceManager deviceManager, IMMDevice device, Dispatcher foregroundDispatcher) { _device = device; _deviceManager = new WeakReference <IAudioDeviceManager>(deviceManager); _dispatcher = foregroundDispatcher; _id = device.GetId(); Trace.WriteLine($"AudioDevice Create {_id}"); if (_device.GetState() == DeviceState.ACTIVE) { _deviceVolume = device.Activate <IAudioEndpointVolume>(); _deviceVolume.RegisterControlChangeNotify(this); _deviceVolume.GetMasterVolumeLevelScalar(out _volume); _isMuted = _deviceVolume.GetMute() != 0; _isRegistered = true; _meter = device.Activate <IAudioMeterInformation>(); _channels = new AudioDeviceChannelCollection(_deviceVolume, _dispatcher); _sessions = new AudioDeviceSessionCollection(this, _device, _dispatcher); _sessionFilter = new FilteredCollectionChain <IAudioDeviceSession>(_sessions.Sessions, _dispatcher); Groups = _sessionFilter.Items; } else { Groups = new ObservableCollection <IAudioDeviceSession>(); } ReadProperties(); }
void IMMNotificationClient.OnDeviceAdded(string pwstrDeviceId) { TraceLine($"OnDeviceAdded {pwstrDeviceId}"); if (!_devices.TryFind(pwstrDeviceId, out IAudioDevice unused)) { try { IMMDevice device = _enumerator.GetDevice(pwstrDeviceId); if (((IMMEndpoint)device).GetDataFlow() == Flow) { var newDevice = new AudioDevice(this, device); _dispatcher.Invoke((Action)(() => { // We must check again on the UI thread to avoid adding a duplicate device. if (!_devices.TryFind(pwstrDeviceId, out IAudioDevice unused1)) { _devices.Add(newDevice); } })); } } catch (Exception ex) { // We catch Exception here because IMMDevice::Activate can return E_POINTER/NullReferenceException, as well as other expcetions listed here: // https://docs.microsoft.com/en-us/dotnet/framework/interop/how-to-map-hresults-and-exceptions TraceLine($"{ex}"); } } }
internal MMDevice(IMMDevice realDevice) { _RealDevice = realDevice; GetPropertyInformation(); Marshal.ThrowExceptionForHR(_RealDevice.GetId(out _id)); IMMEndpoint ep = _RealDevice as IMMEndpoint; Marshal.ThrowExceptionForHR(ep.GetDataFlow(out _dataFlow)); Marshal.ThrowExceptionForHR(_RealDevice.GetState(out _state)); if (_PropertyStore.Contains(PKEY.PKEY_DeviceInterface_FriendlyName)) { _friendlyName = (string)_PropertyStore[PKEY.PKEY_DeviceInterface_FriendlyName].Value; } if (_PropertyStore.Contains(PKEY.PKEY_DeviceInterface_Icon)) { var iconPath = (string)_PropertyStore[PKEY.PKEY_DeviceInterface_Icon].Value; _icon = DeviceIconHelper.GetIconByPath(iconPath); } if (_PropertyStore.Contains(PKEY.PKEY_DeviceInterface_RealName)) { var nameValue = _PropertyStore[PKEY.PKEY_DeviceInterface_RealName].Value; if (nameValue is string s) { _realName = s; } } }
public void Dispose() { try { Stop(); } catch { } lock (mutex) { Cleanup(); if (audioClient != null) { Marshal.ReleaseComObject(audioClient); audioClient = null; } if (endpoint != null) { Marshal.ReleaseComObject(endpoint); endpoint = null; } if (enumerator != null) { Marshal.ReleaseComObject(enumerator); enumerator = null; } isInited = false; buffers = null; thread = null; i8Buf = null; i16Buf = null; i32Buf = null; f32Buf = null; f64Buf = null; } }
internal static MMDevice CreateFromIMMDevice(IMMDevice immDevice) { var result = new MMDevice(immDevice); // return(result); }
public MMDevice GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role) { IMMDevice _Device = null; Marshal.ThrowExceptionForHR(((IMMDeviceEnumerator)_realEnumerator).GetDefaultAudioEndpoint(dataFlow, role, out _Device)); return(new MMDevice(_Device)); }
public MMDevice GetDefaultAudioEndpoint(DataFlow dataFlow, Role role) { IMMDevice realDevice = null; Marshal.ThrowExceptionForHR(this.realEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out realDevice)); return(new MMDevice(realDevice)); }
public MMDevice GetDevice(string id) { IMMDevice realDevice = null; Marshal.ThrowExceptionForHR(this.realEnumerator.GetDevice(id, out realDevice)); return(new MMDevice(realDevice)); }
private static IAudioEndpointVolume GetMasterVolumeObject() { IAudioEndpointVolume masterVolume = null; IMMDeviceEnumerator deviceEnumerator = null; IMMDevice defautOutDevice = null; try { deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator()); deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out defautOutDevice); Guid IID_IAudioEndpointVolume = typeof(IAudioEndpointVolume).GUID; object o; defautOutDevice.Activate(IID_IAudioEndpointVolume, 0, IntPtr.Zero, out o); masterVolume = (IAudioEndpointVolume)o; } finally { if (defautOutDevice != null) { Marshal.ReleaseComObject(defautOutDevice); } if (deviceEnumerator != null) { Marshal.ReleaseComObject(deviceEnumerator); } } return(masterVolume); }
private void LoadAudioMeterInformation(IMMDevice device) { //This should be all on the COM thread to avoid any //weird lookups on the result COM object not on an STA Thread ComThread.Assert(); object result = null; Exception ex; //Need to catch here, as there is a chance that unauthorized is thrown. //It's not an HR exception, but bubbles up through the .net call stack try { var clsGuid = new Guid(ComIIds.AUDIO_METER_INFORMATION_IID); ex = Marshal.GetExceptionForHR(device.Activate(ref clsGuid, ClsCtx.Inproc, IntPtr.Zero, out result)); } catch (Exception e) { ex = e; } if (ex != null) { ClearAudioMeterInformation(); return; } _audioMeterInformation = new AudioMeterInformation(result as IAudioMeterInformation); }
/// <summary> /// Call this method to release all com objetcs /// </summary> public virtual void Dispose() { if (iAudioEndpoint != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(iAudioEndpoint); iAudioEndpoint = null; } if (oEndPoint != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oEndPoint); oEndPoint = null; } if (imd != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(imd); imd = null; } if (oDevice != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oDevice); oDevice = null; } if (iMde != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(iMde); iMde = null; } if (oEnumerator != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oEnumerator); oEnumerator = null; } }
internal AudioDevice(IMMDevice device) { _device = device; string id; _device.GetId(out id); this.DeviceId = id; IPropertyStore ips; _device.OpenPropertyStore(StorageAccessMode.Read, out ips); var pk = PropertyKeys.DeviceFriendlyName; PropertyVariant val; ips.GetValue(ref pk, out val); this.Name = val.Value.ToString(); }
internal MMDevice(IMMDevice realDevice) { _RealDevice = realDevice; GetPropertyInformation(); Marshal.ThrowExceptionForHR(_RealDevice.GetId(out _id)); IMMEndpoint ep = _RealDevice as IMMEndpoint; Marshal.ThrowExceptionForHR(ep.GetDataFlow(out _dataFlow)); Marshal.ThrowExceptionForHR(_RealDevice.GetState(out _state)); if (_PropertyStore.Contains(PKEY.PKEY_DeviceInterface_FriendlyName)) _friendlyName = (string)_PropertyStore[PKEY.PKEY_DeviceInterface_FriendlyName].Value; }
private static AudioDevice CreateDevice(IMMDevice dev) { if (dev == null) return null; string id; dev.GetId(out id); DEVICE_STATE state; dev.GetState(out state); Dictionary<string, object> properties = new Dictionary<string, object>(); IPropertyStore store; dev.OpenPropertyStore(STGM.STGM_READ, out store); if (store != null) { int propCount; store.GetCount(out propCount); for (int j = 0; j < propCount; j++) { PROPERTYKEY pk; if (store.GetAt(j, out pk) == 0) { PROPVARIANT value = new PROPVARIANT(); int hr = store.GetValue(ref pk, ref value); object v = value.GetValue(); try { if (value.vt != VARTYPE.VT_BLOB) // for some reason, this fails? { PropVariantClear(ref value); } } catch { } string name = pk.ToString(); properties[name] = v; } } } return new AudioDevice(id, (AudioDeviceState)state, properties); }
internal CoreAudioDevice(IMMDevice device, IAudioController<CoreAudioDevice> controller) : base(controller) { ComThread.Assert(); _device = device; if (device == null) throw new ArgumentNullException("device"); LoadProperties(device); ReloadAudioMeterInformation(device); ReloadAudioEndpointVolume(device); controller.AudioDeviceChanged += new EventHandler<DeviceChangedEventArgs>(EnumeratorOnAudioDeviceChanged) .MakeWeak(x => { controller.AudioDeviceChanged -= x; }); }
private void LoadProperties(IMMDevice device) { ComThread.Assert(); //Load values Marshal.ThrowExceptionForHR(device.GetId(out _realId)); Marshal.ThrowExceptionForHR(device.GetState(out _state)); // ReSharper disable once SuspiciousTypeConversion.Global var ep = device as IMMEndpoint; if (ep != null) ep.GetDataFlow(out _dataFlow); GetPropertyInformation(device); }
internal MMDevice(IMMDevice realDevice) { _RealDevice = realDevice; }
private void ReloadAudioMeterInformation(IMMDevice device) { ComThread.BeginInvoke(() => { LoadAudioMeterInformation(device); }); }
private void ReloadAudioEndpointVolume(IMMDevice device) { ComThread.BeginInvoke(() => { LoadAudioEndpointVolume(device); if (AudioEndpointVolume != null) AudioEndpointVolume.OnVolumeNotification += AudioEndpointVolume_OnVolumeNotification; }); }
internal MMDevice() { _RealDevice = null; }
public virtual void Dispose() { if (iAudioEndpoint != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(iAudioEndpoint); iAudioEndpoint = null; } if (oEndPoint != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oEndPoint); oEndPoint = null; } if (imd != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(imd); imd = null; } if (oDevice != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oDevice); oDevice = null; } if (iMde != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(iMde); iMde = null; } if (oEnumerator != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oEnumerator); oEnumerator = null; } }
/// <summary> /// Call this method to release all com objetcs /// </summary> public virtual void Dispose() { /* if (delMixerChange != null && iAudioEndpoint != null) { iAudioEndpoint.UnregisterControlChangeNotify(delMixerChange); } */ if (iAudioEndpoint != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(iAudioEndpoint); iAudioEndpoint = null; } if (oEndPoint != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oEndPoint); oEndPoint = null; } if (imd != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(imd); imd = null; } if (oDevice != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oDevice); oDevice = null; } //System.Runtime.InteropServices.Marshal.ReleaseComObject(pCollection); if (iMde != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(iMde); iMde = null; } if (oEnumerator != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oEnumerator); oEnumerator = null; } }
//public event MixerChangedEventHandler MixerChanged; #region Class Constructor and Dispose public methods /// <summary> /// Constructor /// </summary> public EndpointVolume() { const uint CLSCTX_INPROC_SERVER = 1; Guid clsid = new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"); Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046"); oEnumerator = null; uint hResult = CoCreateInstance(ref clsid, null, CLSCTX_INPROC_SERVER, ref IID_IUnknown, out oEnumerator); if (hResult != 0 || oEnumerator == null) { throw new Exception("CoCreateInstance() pInvoke failed"); } iMde = oEnumerator as IMMDeviceEnumerator; if (iMde == null) { throw new Exception("COM cast failed to IMMDeviceEnumerator"); } IntPtr pDevice = IntPtr.Zero; int retVal = iMde.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eConsole, ref pDevice); if (retVal != 0) { throw new Exception("IMMDeviceEnumerator.GetDefaultAudioEndpoint()"); } int dwStateMask = DEVICE_STATE_ACTIVE | DEVICE_STATE_NOTPRESENT | DEVICE_STATE_UNPLUGGED; IntPtr pCollection = IntPtr.Zero; retVal = iMde.EnumAudioEndpoints(EDataFlow.eRender, dwStateMask, ref pCollection); if (retVal != 0) { throw new Exception("IMMDeviceEnumerator.EnumAudioEndpoints()"); } oDevice = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(pDevice); imd = oDevice as IMMDevice; if (imd == null) { throw new Exception("COM cast failed to IMMDevice"); } Guid iid = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A"); uint dwClsCtx = (uint)CLSCTX.CLSCTX_ALL; IntPtr pActivationParams = IntPtr.Zero; IntPtr pEndPoint = IntPtr.Zero; retVal = imd.Activate(ref iid, dwClsCtx, pActivationParams, ref pEndPoint); if (retVal != 0) { throw new Exception("IMMDevice.Activate()"); } oEndPoint = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(pEndPoint); iAudioEndpoint = oEndPoint as IAudioEndpointVolume; if (iAudioEndpoint == null) { throw new Exception("COM cast failed to IAudioEndpointVolume"); } /* delMixerChange = new DelegateMixerChange(MixerChange); retVal = iAudioEndpoint.RegisterControlChangeNotify(delMixerChange); if (retVal != 0) { throw new Exception("iAudioEndpoint.RegisterControlChangeNotify(delMixerChange)"); } */ }
internal MMDevice(IMMDevice realDevice) { deviceInterface = realDevice; }
internal AudioDevice(IMMDevice underlyingDevice) { _underlyingDevice = underlyingDevice; }
private void Dispose(bool disposing) { ClearAudioEndpointVolume(); ClearAudioMeterInformation(); _device = null; }
/// <summary> /// Will attempt to load the properties from the MMDevice. If it can't open, or the device is in /// an invalid state it will continue to use it's current internal property cache /// </summary> /// <param name="device"></param> public void TryLoadFrom(IMMDevice device) { var properties = GetProperties(device); if (properties.Count > 0) _properties = properties; }
private Dictionary<PropertyKey, object> GetProperties(IMMDevice device) { var properties = new Dictionary<PropertyKey, object>(); //Opening in write mode, can cause exceptions to be thrown when not run as admin. //This tries to open in write mode if available try { Marshal.ThrowExceptionForHR(device.OpenPropertyStore(StorageAccessMode.ReadWrite, out _propertyStoreInteface)); Mode = AccessMode.ReadWrite; } catch { Debug.WriteLine("Cannot open property store in write mode"); } if (_propertyStoreInteface == null) { Marshal.ThrowExceptionForHR(device.OpenPropertyStore(StorageAccessMode.Read, out _propertyStoreInteface)); Mode = AccessMode.Read; } try { uint count; _propertyStoreInteface.GetCount(out count); for (uint i = 0; i < count; i++) { PropertyKey key; PropVariant variant; _propertyStoreInteface.GetAt(i, out key); _propertyStoreInteface.GetValue(ref key, out variant); if (variant.IsSupported()) properties.Add(key, variant.Value); } } catch { Debug.WriteLine("Cannot get property values"); return new Dictionary<PropertyKey, object>(); } return properties; }
internal AEDev() { IMMDevice _Device = null; Marshal.ThrowExceptionForHR(((IMMDeviceEnumerator)_realEnumerator).GetDefaultAudioEndpoint(0, 1, out _Device)); _RealDevice = _Device; object result; Marshal.ThrowExceptionForHR(_RealDevice.Activate(ref IID_IAudioEndpointVolume, CTX.ALL, IntPtr.Zero, out result)); _AudioEndPointVolume = result as IAudioEndpointVolume; _CallBack = new AudioEndpointVolumeCallback(this); Marshal.ThrowExceptionForHR(_AudioEndPointVolume.RegisterControlChangeNotify(_CallBack)); }
private void LoadAudioEndpointVolume(IMMDevice device) { //Don't even bother looking up volume for disconnected devices if (!State.HasFlag(DeviceState.Active)) { ClearAudioEndpointVolume(); return; } //This should be all on the COM thread to avoid any //weird lookups on the result COM object not on an STA Thread ComThread.Assert(); object result = null; Exception ex; //Need to catch here, as there is a chance that unauthorized is thrown. //It's not an HR exception, but bubbles up through the .net call stack try { var clsGuid = new Guid(ComIIds.AUDIO_ENDPOINT_VOLUME_IID); ex = Marshal.GetExceptionForHR(device.Activate(ref clsGuid, ClsCtx.Inproc, IntPtr.Zero, out result)); } catch (Exception e) { ex = e; } if (ex != null) { ClearAudioEndpointVolume(); return; } _audioEndpointVolume = new AudioEndpointVolume(result as IAudioEndpointVolume); }
public void GetDevice(string deviceId, out IMMDevice device) { _inner.GetDevice(deviceId, out device); }
private void GetPropertyInformation(IMMDevice device) { ComThread.Assert(); if (_properties == null) _properties = new CachedPropertyDictionary(); //Don't try to load properties for a device that doesn't exist if (State == DeviceState.NotPresent) return; _properties.TryLoadFrom(device); }
public void GetDefaultAudioEndpoint(DataFlow dataFlow, Role role, out IMMDevice device) { _inner.GetDefaultAudioEndpoint(dataFlow, role, out device); }