Enumerating Sound Recording Devices
In one of my projects I need to enumerate through all the sound recording devices installed in my system. Now to do so logic is simple.
int count := Get the count of sound in devices;
for each i in [0, count - 1]
get the device capabilities(i);
print the name(i);
end for
Retrieving the total count of sound recording devices was the simpler part. Following P/Invoke declaration was enough
[DllImport("winmm.dll")]
public static extern int waveInGetNumDevs();
The tough part was to get the device capabilities. The relevant API was
MMRESULT waveInGetDevCaps(
UINT_PTR uDeviceID,
LPWAVEINCAPS pwic,
UINT cbwic
);
Although this link describes the data structure of LPWAVEINCAPS fairly well, the C# declaration was really hard to guess. After a lot of trial & error I finally came accross following signature
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public sruct WaveInCaps
{
public short wMid;
public short wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public char[] szPname;
public uint dwFormats;
public short wChannels;
public short wReserved1;
}
Keep an eye on the SizeConst=32(MAXPNAMELEN) attribute for the szPname's marsalling requirements. Rest of the story is simple
int
waveInDevicesCount = WaveLib.WaveNative.waveInGetNumDevs();
if (waveInDevicesCount > 0)
{
for (uint uDeviceID = 0; uDeviceID < waveInDevicesCount; uDeviceID++)
{
WaveLib.WaveInCaps waveInCaps = new WaveLib.WaveInCaps();
WaveLib.WaveNative.waveInGetDevCaps(uDeviceID,
out waveInCaps,
Marshal.SizeOf(typeof(WaveLib.WaveInCaps)));
cmbWaveInDevices.Items.Add(new string(waveInCaps.szPname));
}
}
End of quick'n'dirty post