Skip to content

Instantly share code, notes, and snippets.

@martindevans
Created February 24, 2022 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martindevans/59bf1202ace94186807dab53dbf5444c to your computer and use it in GitHub Desktop.
Save martindevans/59bf1202ace94186807dab53dbf5444c to your computer and use it in GitHub Desktop.
[CanBeNull]
private static AudioDevice ChooseAudioDevice([CanBeNull] string name)
{
var criterion = MediaDeviceCriteria.AudioDevice;
var query = new MediaDeviceQuery(criterion);
var useDefault = string.IsNullOrWhiteSpace(name);
AudioDevice firstDevice = null;
for (var i = 0; i < query.count; i++)
{
// Skip invalid devices
if (!(query[i] is AudioDevice audioDevice))
continue;
// Keep track of the first valid device, in case we don't find anything better
if (firstDevice == null)
firstDevice = audioDevice;
// If the default has been requested then use the default as soon as we find it
if (useDefault && audioDevice.defaultForMediaType)
return audioDevice;
// Use the device if the name matches
if (!useDefault && audioDevice.name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
return audioDevice;
}
// None of the device match the name, use the first available device
return firstDevice;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment