Dev*_*per 12 .net c# headphones audio-device
没有示例如何通过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"]);
}
Run Code Online (Sandbox Code Playgroud)
有人会很高兴提供它吗?
谢谢!
Yan*_*ton 10
我不建议您自己使用COM + API.
Install-Package NAudio
Run Code Online (Sandbox Code Playgroud)
您应该能够枚举具有插入/拔出状态的音频设备,如下所示:
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());
Run Code Online (Sandbox Code Playgroud)
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) { }
}
Run Code Online (Sandbox Code Playgroud)
应该产生类似的结果:
我认为它在上面的截图中检测到插拔两次的原因是因为在Macbook上他们使用一个插孔用于麦克风和耳机.
使用IMMDeviceEnumerator :: RegisterEndpointNotificationCallback方法可以检测此类更改.
如果你想在C#中处理这个问题,你需要一个托管包装器,它已经由Akos Mattiassich实现.你可以在这里找到一个例子:MMAudioDeviceApi周围的托管包装器
他说:
该程序可以在所选设备上播放测试声音,并在更改时自动更新列表,例如.通过控制面板或在物理上插入新设备的情况下.
| 归档时间: |
|
| 查看次数: |
6538 次 |
| 最近记录: |