I wouldn't recommend using the COM+ API yourself.
Take a look at the NAudio NuGet package:
Install-Package NAudio
You should be able to enumerate the audio devices with their plugged/unplugged states as follows:
var enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator();
// Allows you to enumerate rendering devices in certain states
var endpoints = enumerator.EnumerateAudioEndPoints(
DataFlow.Render,
DeviceState.Unplugged | DeviceState.Active);
foreach (var endpoint in endpoints)
{
Console.WriteLine("{0} - {1}", endpoint.DeviceFriendlyName, endpoint.State);
}
// Aswell as hook to the actual event
enumerator.RegisterEndpointNotificationCallback(new NotificationClient());
Where NotificationClient is implemented as follows:
class NotificationClient : NAudio.CoreAudioApi.Interfaces.IMMNotificationClient
{
void IMMNotificationClient.OnDeviceStateChanged(string deviceId, DeviceState newState)
{
Console.WriteLine("OnDeviceStateChanged
Device Id -->{0} : Device State {1}", deviceId, newState);
}
void IMMNotificationClient.OnDeviceAdded(string pwstrDeviceId) { }
void IMMNotificationClient.OnDeviceRemoved(string deviceId) { }
void IMMNotificationClient.OnDefaultDeviceChanged(DataFlow flow, Role role, string defaultDeviceId) { }
void IMMNotificationClient.OnPropertyValueChanged(string pwstrDeviceId, PropertyKey key) { }
}
Should produce a similar result to:
I think the reason why it detects plugging/unplugging twice in the above screenshot is because on Macbook they use one jack for both mic and headphones.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…