using NAudio.CoreAudioApi.Interfaces; using NAudio.Wasapi.CoreAudioApi.Interfaces; using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace NAudio.Wasapi.CoreAudioApi { internal class ActivateAudioInterfaceCompletionHandler : IActivateAudioInterfaceCompletionHandler, IAgileObject { private Action initializeAction; private TaskCompletionSource tcs = new TaskCompletionSource(); public ActivateAudioInterfaceCompletionHandler( Action initializeAction) { this.initializeAction = initializeAction; } public void ActivateCompleted(IActivateAudioInterfaceAsyncOperation activateOperation) { // First get the activation results, and see if anything bad happened then activateOperation.GetActivateResult(out int hr, out object unk); if (hr != 0) { tcs.TrySetException(Marshal.GetExceptionForHR(hr, new IntPtr(-1))); return; } var pAudioClient = (IAudioClient2)unk; // Next try to call the client's (synchronous, blocking) initialization method. try { initializeAction(pAudioClient); tcs.SetResult(pAudioClient); } catch (Exception ex) { tcs.TrySetException(ex); } } public TaskAwaiter GetAwaiter() { return tcs.Task.GetAwaiter(); } } }