Detect if headphones are plugged in or not via C#

后端 未结 3 1543
不知归路
不知归路 2020-12-02 21:53

There is no example how to detect if headphones are plugged in or not via C#.

I assume should be some event for that...

Does make sense to use WMI?



        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 22:06

    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\n 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.

提交回复
热议问题