Search code examples
c#windows-runtimewindows-phone

AudioDevice: recording sound using MediaCapture in WinRT/WP 8.1


I'm currently building an app that uses the WinRT MediaCapture API to record audio and take a photo.

The code I have that initialises the MediaCapture and selects the right devices looks like this:

try
  {
    _captureManager = new MediaCapture();
    string camera = "";
    foreach (var device in await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture))
    {
      switch (device.EnclosureLocation.Panel)
      {
        case Windows.Devices.Enumeration.Panel.Back:
          camera = device.Id;
          continue;
      }
    }

    var mics = await DeviceInformation.FindAllAsync(DeviceClass.AudioCapture);

    var settings = new MediaCaptureInitializationSettings
    {
      PhotoCaptureSource = PhotoCaptureSource.Auto,
      StreamingCaptureMode = StreamingCaptureMode.AudioAndVideo,
      VideoDeviceId = camera,
      AudioDeviceId = mics.First().Id
    };

    await _captureManager.InitializeAsync(settings);

I assumed, wrongly it seems, the first microphone would be the default. However, one device I have found doesn't give you permission to use this microphone, it does however give access to the second. Clearly, this is not a reliable way of selecting a microphone.

Instead, I have now tried this code:

try
  {
    _captureManager = new MediaCapture();
    var camera = "";
    foreach (var device in await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture))
    {
      switch (device.EnclosureLocation.Panel)
      {
        case Windows.Devices.Enumeration.Panel.Back:
          camera = device.Id;
          continue;
      }
    }

    var settings = new MediaCaptureInitializationSettings
    {
      PhotoCaptureSource = PhotoCaptureSource.Auto,
      StreamingCaptureMode = StreamingCaptureMode.AudioAndVideo,
      VideoDeviceId = camera,
    };

    await _captureManager.InitializeAsync(settings);

Not setting an AudioDevice seems to still work using these settings but causes problem on the device I have (it crashes).

This could be device specific but I was wondering if there was a better or advised way of setting up the MediaCapture other than the above?


Solution

  • Try selecting your audio device by using the Windows.Media.Devices.MediaDevice.GetDefaultAudioCaptureId API.

    I would also strongly recommend you subscribe to the Windows.Media.Devices.MediaDevice.DefaultAudioCaptureDeviceChanged event, to handle changing of the default audio capture device, if it applies to your scenario.