/// <summary> /// /// </summary> /// <param name="recognition"></param> /// <param name="recording"></param> /// <param name="exceptionsBag"></param> /// <param name="cancellationToken"></param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> /// <returns></returns> public static async Task BindRecordingAsync( this IStreamingRecognition recognition, IRecording recording, ExceptionsBag?exceptionsBag = null, CancellationToken cancellationToken = default) { recognition = recognition ?? throw new ArgumentNullException(nameof(recognition)); recording = recording ?? throw new ArgumentNullException(nameof(recording)); if (recording.Settings.Format is not AudioFormat.Raw) { if (!recording.Header.Any()) { throw new ArgumentException("recording.Header is empty."); } await recognition.WriteAsync(recording.Header, cancellationToken).ConfigureAwait(false); } if (recording.Data.Any()) { await recognition.WriteAsync(recording.Data, cancellationToken).ConfigureAwait(false); } async void OnDataReceived(object?_, byte[] bytes) { try { await recognition.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); } catch (Exception exception) { exceptionsBag?.OnOccurred(exception); } } void OnStopped(object?o, byte[] bytes) { try { recording.DataReceived -= OnDataReceived; recording.Stopped -= OnStopped; } catch (Exception exception) { exceptionsBag?.OnOccurred(exception); } } recording.DataReceived += OnDataReceived; recording.Stopped += OnStopped; }
/// <summary> /// Waits <seealso cref="IStreamingRecognition.Stopped"/> events. <br/> /// Can be used with <seealso cref="RecordingExtensions.StopWhenSilence"/> extension. /// </summary> /// <param name="recognition"></param> /// <param name="cancellationToken"></param> public static async Task WaitStopAsync( this IStreamingRecognition recognition, CancellationToken cancellationToken = default) { recognition = recognition ?? throw new ArgumentNullException(nameof(recognition)); var source = new TaskCompletionSource <bool>(); using var registration = cancellationToken.Register(() => source.TrySetCanceled()); recognition.Stopped += (_, _) => { source.TrySetResult(true); }; await source.Task.ConfigureAwait(false); }