Search code examples
c#wpfuwpvoice-recording

UWP MediaCapture initialization fails


I'm developing a WPF application where I'm recording audio data with the Windows.Media.Capture.MediaCapture class. It's working if I initialize with or without parameters:

var mediaCapture = new MediaCapture();
await mediaCapture.InitializeAsync();

or I can add which microphone to use (if there are more than one):

var allAudioDevices = await DeviceInformation.FindAllAsync(DeviceClass.AudioCapture);
DeviceInformation microphone = allAudioDevices.FirstOrDefault();

MediaCaptureInitializationSettings mediaInitSettings = new MediaCaptureInitializationSettings {
    AudioDeviceId = microphone.Id,
    StreamingCaptureMode = StreamingCaptureMode.Audio
};

await _mediaCapture.InitializeAsync(mediaInitSettings);

The problem comes when I run my app as a UWP application (with desktop bridge). As a UWP app when it calls the InitializeAsync() method, it always throws an exception with the following (verbose :) ) error message: Element not found. The DeviceInformation object of the microphone is found correctly, so something happens during the initialization of the MediaCapture.

The Microphone capability is set in the manifest file of the bridge project.

What am I doing wrong? I'm also open to use other methods to record the voice.


Solution

  • I figured out that if I run the initialization on the UI thread, it works well:

    await Application.Current.Dispatcher.InvokeAsync(async () => {
        await mediaCapture.InitializeAsync();
    });