Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过C检测耳机是否已插入#_C#_.net_Headphones_Audio Device - Fatal编程技术网

C# 通过C检测耳机是否已插入#

C# 通过C检测耳机是否已插入#,c#,.net,headphones,audio-device,C#,.net,Headphones,Audio Device,没有关于如何通过C#检测耳机是否已插入的示例 我想这应该是一个事件 使用WMI有意义吗 ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\cimv2", "SELECT * FROM Win32_SoundDevice"); foreach (ManagementObj

没有关于如何通过C#检测耳机是否已插入的示例

我想这应该是一个事件

使用WMI有意义吗

 ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\cimv2",
                                                                  "SELECT * FROM Win32_SoundDevice");

foreach (ManagementObject queryObj in searcher.Get())
{
    Console.WriteLine("-----------------------------------");
    Console.WriteLine("Win32_SoundDevice instance");
    Console.WriteLine("-----------------------------------");
    Console.WriteLine("StatusInfo: {0}", queryObj["StatusInfo"]);
}
有人愿意提供吗


谢谢大家!

使用该方法可以检测此类变化

当你想在C#中处理这个问题时,你需要一个已经由Akos Mattiasich实现的托管包装器。你可以在这里找到一个很好的例子:

他说:

该程序可以在选定的设备上播放测试声音,并在更改时自动更新列表,例如通过控制面板或在物理插入新设备的情况下


我不建议您自己使用COM+API

请看一下:

您应该能够列举音频设备的插拔状态,如下所示:

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());
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) { }
}
其中NotificationClient的实现方式如下:

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());
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) { }
}
应产生与以下类似的结果:

我认为它在上面的截图中检测到两次插拔的原因是因为在Macbook上,他们使用一个插孔来连接麦克风和耳机。

下面是一个基于的(最小)Windows窗体应用程序示例,它不需要任何第三方库

无论何时插入/拔出多媒体设备,您都会收到通知。然后,您可以查看设备属性并采取适当的操作。您还可以枚举现有设备并检查耳机是否已插入(请参阅
IsConnected
属性)

创建COM互操作 请注意,示例代码包括相关COM对象的定义。在生产环境中,我可能会为底层mmdevapi.dll创建一个COM互操作程序集。您可以首先从头文件创建类型库(需要安装Windows SDK):

然后,您需要使用
tlbimp.exe
从typelib生成互操作程序集:

tlbimp /out:MMDevAPI.Interop.dll mmdeviceapi.tlb
多媒体通知侦听器示例
使用系统;
使用System.Runtime.InteropServices;
使用System.Collections.Generic;
使用系统诊断;
使用System.Linq;
运用系统反思;
使用System.Runtime.CompilerServices;
使用System.Windows.Forms;
命名空间MultiMediaNotificationListenerSample
{
类主窗口:窗体
{
[状态线程]
私有静态void Main(字符串[]args)
{
使用(var notificationClient=new multimediannotificationlistener())
{
Trace.WriteLine(string.Format(“耳机已连接,{0}”,notificationClient.IsConnected?”:“未连接”);
运行(新的主窗口());
}
}
}
类MultiMediaNotificationListener:imNotificationClient,IDisposable
{
专用只读IMMDeviceEnumerator\u deviceEnumerator;
公共多媒体通知侦听器()
{
if(Environment.OSVersion.Version.Major<6)
{
抛出new NotSupportedException(“此功能仅在Windows Vista或更高版本上受支持。”);
}
_deviceEnumerator=(IMMDeviceEnumerator)新的MMDeviceEnumerator();
_deviceEnumerator.RegisterEndpointNotificationCallback(此);
}
~MultiMediaNotificationListener()
{
处置(虚假);
}
公共图书馆断开了
{
得到
{
IMMDeviceCollection设备采集;
_deviceEnumerator.EnumAudioEndpoints(EDataFlow.eRender,(uint)DeviceState.DEVICE\u STATE\u ACTIVE,out deviceCollection);
单元设备计数=0;
deviceCollection.GetCount(out deviceCount);
对于(uint i=0;i
{
固有变异性;
获取值(ref propertyKey,out属性);
返回新的{Key=PropertyKey.GetKeyName(PropertyKey),Value=property.Value};
})
.Where(@t=>@t.Value!=null);
foreach(属性中的var属性)
{
Trace.WriteLine(string.Format(“{0}\t{1}”,property.Key,property.Value));
}
Marshal.ReleaseComObject(propertyStore);
Marshal.ReleaseComObject(设备);
}
OnDeviceAdded公共无效(字符串设备ID)
{
}