如何关联USB耳机麦克风和耳机/扬声器

时间:2015-05-01 06:36:39

标签: c# .net wmi microphone headset

背景

我需要在软电话应用程序中显示已连接耳机(组合麦克风和耳机)的列表。为了测试我有以下设备:

  • Jabra PRO 9470
  • Plantronics BT300M
  • 罗技G430游戏耳机

用户应该可以从ComboBox选择耳机,而无需单独选择麦克风和耳机。

信息

我知道在哪里可以找到有关麦克风和耳机的信息(在Windows中),但我无法使用WMIMMDevice API来获取信息。

要查找信息,请右键单击任务栏右侧的Sound(扬声器图标),然后选择Playback devices

Headset properties

  1. 双击打开属性窗口或单击Properties
  2. 单击属性窗口中的Properties按钮。
  3. 点击Details标签,在Children中找到ComboBox媒体资源。
  4. 这将给我以下信息:

    SWD\MMDEVAPI\{0.0.0.00000000}.{f2e09e37-8389-46c4-8b2b-53e08b874399}
    SWD\MMDEVAPI\{0.0.1.00000000}.{3402ee6e-d862-47ca-8ab8-bb8254216032}
    

    第一行与我的Headset Earphone (Jabra PRO 9470)和第二行Headset Microphone (Jabra PRO 9470)匹配。

    要在C#中获取相同的信息,我将循环遍历Win32_USBControllerDevice类并输出包含" MMDEVAPI"的所有值。在我的电脑上,它将返回6个值(3个麦克风,3个耳机)。

    foreach (var device in new ManagementObjectSearcher("SELECT * FROM Win32_USBControllerDevice").Get())
    {
        foreach (var property in device.Properties)
        {
            // Gets the value of the property on the device.
            var value = property.Value == null ? string.Empty : property.Value.ToString();
    
            if (value.IndexOf("mmdevapi", StringComparison.OrdinalIgnoreCase) > -1)
            {
                // Output connected USB microphones and earphones.
                Console.WriteLine(property.Value);
            }
        }
    }
    

    作为参考,上面的代码将输出:

    \\PC9018\root\cimv2:Win32_PnPEntity.DeviceID="SWD\\MMDEVAPI\\{0.0.0.00000000}.{F2E09E37-8389-46C4-8B2B-53E08B874399}"
    \\PC9018\root\cimv2:Win32_PnPEntity.DeviceID="SWD\\MMDEVAPI\\{0.0.1.00000000}.{3402EE6E-D862-47CA-8AB8-BB8254216032}"
    \\PC9018\root\cimv2:Win32_PnPEntity.DeviceID="SWD\\MMDEVAPI\\{0.0.0.00000000}.{985F2B5C-2EE2-4733-BBD6-48BFDE2D5582}"
    \\PC9018\root\cimv2:Win32_PnPEntity.DeviceID="SWD\\MMDEVAPI\\{0.0.1.00000000}.{71D824EA-DAE9-4F0D-B673-4425385E3777}"
    \\PC9018\root\cimv2:Win32_PnPEntity.DeviceID="SWD\\MMDEVAPI\\{0.0.0.00000000}.{D29C0970-D515-4F91-9924-F0063CF1A196}"
    \\PC9018\root\cimv2:Win32_PnPEntity.DeviceID="SWD\\MMDEVAPI\\{0.0.1.00000000}.{C4B331E2-C56B-4D9B-A486-2ED6C11FDB8C}"
    

    问题

    我现在面临的一个大问题是,如何将正确的耳机麦克风和耳机关联到Headset对象?

    尝试次数

    我已尝试在Google和StackOverflow上搜索答案或提示,但我无法使用WMIMMDevice API在麦克风和耳机之间找到任何共同点或关系。

    如果有办法创建Dictionary<string, List<string>>,其中Key是物理设备或USB端口唯一的,Value是关联的Win32_PnPEntity.DeviceID列表},然后我找不到它。

    星球大战日的精神中,几天之内:&#34; 帮助我,StackOverflow。你是我唯一的希望。&#34;

1 个答案:

答案 0 :(得分:3)

NAudio和Windows注册表的帮助下,我自己找到了答案。问题中的代码仍然是正确的,但NAudio使它更容易。

我在Windows注册表中找到了我的问题的关键:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render

每个设备都有一个名为{b3f8fa53-0004-438e-9003-51a46e139bfc},2的属性,其值类似于此{1}.USB\VID_047F&PID_0416&MI_00\7&21995D75&0&0000

这看起来是一个独特的硬件ID,由耳机麦克风和耳机共享(与问题中的Children属性相同)。

解决方案

具有单个方法的界面,用于查找和返回耳机列表。

public interface IHeadsetLocator
{
    /// <summary>
    /// Locate all connected audio devices based on the given state.
    /// </summary>
    /// <param name="deviceState"></param>
    /// <returns></returns>
    IReadOnlyCollection<Headset> LocateConnectedAudioDevices(DeviceState deviceState = DeviceState.Active);
}

完整的实施。真正的魔法发生在GetHardwareToken方法的帮助下。

public class HeadsetLocator : IHeadsetLocator
{
    /// <summary>
    /// Locate all connected audio devices based on the given state.
    /// </summary>
    /// <param name="deviceState"></param>
    /// <returns></returns>
    public IReadOnlyCollection<Headset> LocateConnectedAudioDevices(DeviceState deviceState = DeviceState.Active)
    {
        var enumerator = new MMDeviceEnumerator();
        var relatedAudioDevices = new ConcurrentDictionary<string, List<MMDevice>>();
        var headsets = new List<Headset>();

        // Locate all connected audio devices.
        foreach (var device in enumerator.EnumerateAudioEndPoints(DataFlow.All, deviceState))
        {
            // Gets the DataFlow and DeviceID from the connected audio device.
            var index = device.ID.LastIndexOf('.');
            var dataFlow = device.ID.Substring(0, index).Contains("0.0.0") ? DataFlow.Render : DataFlow.Capture;
            var deviceId = device.ID.Substring(index + 1);

            // Gets the unique hardware token.
            var hardwareToken = GetHardwareToken(dataFlow, deviceId);

            var audioDevice = relatedAudioDevices.GetOrAdd(hardwareToken, o => new List<MMDevice>());
            audioDevice.Add(device);
        }

        // Combines the related devices into a headset object.
        foreach (var devicePair in relatedAudioDevices)
        {
            var capture = devicePair.Value.FirstOrDefault(o => o.ID.Contains("0.0.1"));
            var render = devicePair.Value.FirstOrDefault(o => o.ID.Contains("0.0.0"));

            if (capture != null && render != null)
            {
                headsets.Add(new Headset("Headset", render.DeviceFriendlyName, capture, render));
            }
        }

        return new ReadOnlyCollection<Headset>(headsets);
    }

    /// <summary>
    /// Gets the token of the USB device.
    /// </summary>
    /// <param name="dataFlow"></param>
    /// <param name="audioDeviceId"></param>
    /// <returns></returns>
    public string GetHardwareToken(DataFlow dataFlow, string audioDeviceId)
    {
        using (var registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
        {
            var captureKey = registryKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\" + dataFlow + @"\" + audioDeviceId + @"\Properties");
            if (captureKey != null)
            {
                return captureKey.GetValue("{b3f8fa53-0004-438e-9003-51a46e139bfc},2") as string;
            }
        }

        return null;
    }
}

我希望这会在类似的情况下帮助其他人。

快乐编码