c# 获取设备列表

  1. NAudio

            var enumerator = new MMDeviceEnumerator();
            var devices = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
            foreach (var device in devices)
            {
                Console.WriteLine(device.FriendlyName);
            }

还可以判断设备类型、获取所有激活中的设备

 /// <summary>
 /// 判断设备是否为麦克风
 /// </summary>
 static bool IsMicrophone(MMDevice device)
 {
     try
     {
         // 获取设备形态属性
         var prop = device.Properties[PropertyKeys.PKEY_AudioEndpoint_FormFactor];
         if (prop == null) return false;

         // 检查是否为麦克风(EndpointFormFactor.Microphone = 3)
         var formFactor = (EndpointFormFactor)((uint)prop.Value);
         return formFactor == EndpointFormFactor.Microphone;
     }
     catch
     {
         return false; // 异常时默认非麦克风
     }
 }

 public enum EndpointFormFactor
 {
     
            RemoteNetworkDevice = 0,
            Speakers,
            LineLevel,
            Headphones,
            Microphone,
            Headset,
            Handset,
            UnknownDigitalPassthrough,
            SPDIF,
            DigitalAudioDisplayDevice,
            UnknownFormFactor,
            EndpointFormFactor_enum_count
 }

 // 创建设备枚举器
 var enumerator = new MMDeviceEnumerator();

 // 获取所有输入设备(麦克风属于输入设备)
 var captureDevices = enumerator.EnumerateAudioEndPoints(
     DataFlow.Capture,    // 输入设备
     DeviceState.Active      // 包含所有状态的设备
 );

 // 筛选出麦克风
 var microphones = captureDevices
     .Cast<MMDevice>()
     .Where(device => IsMicrophone(device))
     .ToList();

 // 输出结果
 Trace.WriteLine($"找到 {microphones.Count} 个麦克风:");
 foreach (var mic in microphones)
 {
     Trace.WriteLine($"名称: {mic.FriendlyName}");
     Trace.WriteLine($"设备ID: {mic.ID}");
     Trace.WriteLine($"状态: {mic.State}");
     Trace.WriteLine("------------------");
     mic.Dispose(); // 释放资源
 }
  1. WIN32
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct WAVEINCAPS
{
    public ushort wMid;
    public ushort wPid;
    public uint vDriverVersion;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string szPname;
    public uint dwFormats;
    public ushort wChannels;
    public ushort wReserved1;
}

[DllImport("winmm.dll", EntryPoint = "waveInGetNumDevs")]
public static extern int WaveInGetNumDevs();

[DllImport("winmm.dll", EntryPoint = "waveInGetDevCaps", CharSet = CharSet.Auto)]
public static extern int WaveInGetDevCaps(int uDeviceID, ref WAVEINCAPS caps, int cb);


   int deviceCount = WaveInGetNumDevs();
   for (int i = 0; i < deviceCount; i++)
   {
       WAVEINCAPS caps = new WAVEINCAPS();
       int result = WaveInGetDevCaps(i, ref caps, Marshal.SizeOf(typeof(WAVEINCAPS)));
       if (result == 0) // 0表示成功
       {
           Console.WriteLine($"Device {i}: {caps.szPname}");
       }
   }

[参考]
endpointFormFactor 枚举 (mmdeviceapi.h)

posted @ 2025-03-01 17:33  Hey,Coder!  阅读(9)  评论(0编辑  收藏  举报