-
Notifications
You must be signed in to change notification settings - Fork 491
SpeechToText AutostopSilenceTimeout #3111
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
811b58c
7f98647
36edccb
fe6d968
96fdd51
31eb967
23646f6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,11 +1,13 @@ | ||||||
| using AVFoundation; | ||||||
| using Microsoft.Maui.Dispatching; | ||||||
| using Speech; | ||||||
|
|
||||||
| namespace CommunityToolkit.Maui.Media; | ||||||
|
|
||||||
| public sealed partial class OfflineSpeechToTextImplementation | ||||||
| { | ||||||
| AVAudioEngine? audioEngine; | ||||||
| readonly AVAudioEngine audioEngine = new(); | ||||||
| IDispatcherTimer? silenceTimer; | ||||||
| SFSpeechRecognizer? speechRecognizer; | ||||||
| SFSpeechRecognitionTask? recognitionTask; | ||||||
| SFSpeechAudioBufferRecognitionRequest? liveSpeechRequest; | ||||||
|
|
@@ -19,12 +21,11 @@ public sealed partial class OfflineSpeechToTextImplementation | |||||
| /// <inheritdoc /> | ||||||
| public ValueTask DisposeAsync() | ||||||
| { | ||||||
| audioEngine?.Dispose(); | ||||||
| audioEngine.Dispose(); | ||||||
| speechRecognizer?.Dispose(); | ||||||
| liveSpeechRequest?.Dispose(); | ||||||
| recognitionTask?.Dispose(); | ||||||
|
|
||||||
| audioEngine = null; | ||||||
| speechRecognizer = null; | ||||||
| liveSpeechRequest = null; | ||||||
| recognitionTask = null; | ||||||
|
|
@@ -41,12 +42,6 @@ public Task<bool> RequestPermissions(CancellationToken cancellationToken = defau | |||||
| return taskResult.Task.WaitAsync(cancellationToken); | ||||||
| } | ||||||
|
|
||||||
| static Task<bool> IsSpeechPermissionAuthorized(CancellationToken cancellationToken) | ||||||
| { | ||||||
| cancellationToken.ThrowIfCancellationRequested(); | ||||||
| return Task.FromResult(SFSpeechRecognizer.AuthorizationStatus is SFSpeechRecognizerAuthorizationStatus.Authorized); | ||||||
| } | ||||||
|
|
||||||
| static void InitializeAvAudioSession(out AVAudioSession sharedAvAudioSession) | ||||||
| { | ||||||
| sharedAvAudioSession = AVAudioSession.SharedInstance(); | ||||||
|
|
@@ -62,10 +57,77 @@ static void InitializeAvAudioSession(out AVAudioSession sharedAvAudioSession) | |||||
|
|
||||||
| void InternalStopListening() | ||||||
| { | ||||||
| audioEngine?.InputNode.RemoveTapOnBus(0); | ||||||
| audioEngine?.Stop(); | ||||||
| silenceTimer?.Tick -= OnSilenceTimerTick; | ||||||
| silenceTimer?.Stop(); | ||||||
| liveSpeechRequest?.EndAudio(); | ||||||
| recognitionTask?.Cancel(); | ||||||
| recognitionTask?.Finish(); | ||||||
| audioEngine.Stop(); | ||||||
| audioEngine.InputNode.RemoveTapOnBus(0); | ||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Two concerns here:
For the race condition, we can add a new field, void InternalStopListening()
{
lock(stopListeningLock)
{
}
}For We could always check first to see if the AudioEngine is Running before executing this code: if (audioEngine.Running)
{
audioEngine.Stop();
audioEngine.InputNode.RemoveTapOnBus(0);
} |
||||||
|
|
||||||
| OnSpeechToTextStateChanged(CurrentState); | ||||||
|
|
||||||
| recognitionTask?.Dispose(); | ||||||
| speechRecognizer?.Dispose(); | ||||||
| liveSpeechRequest?.Dispose(); | ||||||
|
|
||||||
| speechRecognizer = null; | ||||||
| liveSpeechRequest = null; | ||||||
| recognitionTask = null; | ||||||
| } | ||||||
|
|
||||||
| void OnSilenceTimerTick(object? sender, EventArgs e) | ||||||
| { | ||||||
| InternalStopListening(); | ||||||
| } | ||||||
|
Comment on lines
+78
to
+81
|
||||||
|
|
||||||
| SFSpeechRecognitionTask CreateSpeechRecognizerTask(SFSpeechRecognizer sfSpeechRecognizer, SFSpeechAudioBufferRecognitionRequest sfSpeechAudioBufferRecognitionRequest) | ||||||
| { | ||||||
| int currentIndex = 0; | ||||||
| return sfSpeechRecognizer.GetRecognitionTask(sfSpeechAudioBufferRecognitionRequest, (result, err) => | ||||||
| { | ||||||
| if (err is not null) | ||||||
| { | ||||||
| currentIndex = 0; | ||||||
| InternalStopListening(); | ||||||
| OnRecognitionResultCompleted(SpeechToTextResult.Failed(new Exception(err.LocalizedDescription))); | ||||||
| } | ||||||
| else | ||||||
| { | ||||||
| if (result.Final) | ||||||
| { | ||||||
| currentIndex = 0; | ||||||
| InternalStopListening(); | ||||||
| OnRecognitionResultCompleted(SpeechToTextResult.Success(result.BestTranscription.FormattedString)); | ||||||
| } | ||||||
| else | ||||||
| { | ||||||
| RestartTimer(); | ||||||
| if (currentIndex <= 0) | ||||||
| { | ||||||
| OnSpeechToTextStateChanged(CurrentState); | ||||||
| } | ||||||
VladislavAntonyuk marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
|
||||||
| currentIndex++; | ||||||
| OnRecognitionResultUpdated(result.BestTranscription.FormattedString); | ||||||
VladislavAntonyuk marked this conversation as resolved.
Show resolved
Hide resolved
Comment on lines
+85
to
+111
|
||||||
| } | ||||||
| } | ||||||
| }); | ||||||
| } | ||||||
|
|
||||||
| void InitSilenceTimer(SpeechToTextOptions options) | ||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's use
Suggested change
|
||||||
| { | ||||||
| if (options.AutoStopSilenceTimeout < TimeSpan.MaxValue && options.AutoStopSilenceTimeout > TimeSpan.Zero) | ||||||
| { | ||||||
| silenceTimer = Dispatcher.GetForCurrentThread()?.CreateTimer(); | ||||||
| silenceTimer?.Tick += OnSilenceTimerTick; | ||||||
| silenceTimer?.Interval = options.AutoStopSilenceTimeout; | ||||||
| silenceTimer?.Start(); | ||||||
| } | ||||||
| } | ||||||
VladislavAntonyuk marked this conversation as resolved.
Show resolved
Hide resolved
VladislavAntonyuk marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
|
||||||
| void RestartTimer() | ||||||
| { | ||||||
| silenceTimer?.Stop(); | ||||||
| silenceTimer?.Start(); | ||||||
| } | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -53,7 +53,12 @@ static Intent CreateSpeechIntent(SpeechToTextOptions options) | |||||
| intent.PutExtra(RecognizerIntent.ExtraLanguage, javaLocale); | ||||||
| intent.PutExtra(RecognizerIntent.ExtraLanguagePreference, javaLocale); | ||||||
| intent.PutExtra(RecognizerIntent.ExtraOnlyReturnLanguagePreference, javaLocale); | ||||||
|
|
||||||
| if (options.AutoStopSilenceTimeout < TimeSpan.MaxValue && options.AutoStopSilenceTimeout > TimeSpan.Zero) | ||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. After we add the bounds-check to
Suggested change
|
||||||
| { | ||||||
| intent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, (long)options.AutoStopSilenceTimeout.TotalMilliseconds); | ||||||
| intent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, (long)options.AutoStopSilenceTimeout.TotalMilliseconds); | ||||||
| } | ||||||
|
|
||||||
| return intent; | ||||||
| } | ||||||
|
|
||||||
|
|
||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,4 @@ | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Globalization; | ||
| using AVFoundation; | ||
| using Speech; | ||
|
|
||
|
|
@@ -8,7 +7,7 @@ namespace CommunityToolkit.Maui.Media; | |
| /// <inheritdoc /> | ||
| public sealed partial class OfflineSpeechToTextImplementation | ||
| { | ||
| [MemberNotNull(nameof(audioEngine), nameof(recognitionTask), nameof(liveSpeechRequest))] | ||
| [MemberNotNull(nameof(recognitionTask), nameof(liveSpeechRequest))] | ||
| Task InternalStartListening(SpeechToTextOptions options, CancellationToken token = default) | ||
| { | ||
| speechRecognizer = new SFSpeechRecognizer(NSLocale.FromLocaleIdentifier(options.Culture.Name)); | ||
|
|
@@ -19,10 +18,6 @@ Task InternalStartListening(SpeechToTextOptions options, CancellationToken token | |
| throw new ArgumentException("Speech recognizer is not available"); | ||
| } | ||
|
|
||
| audioEngine = new AVAudioEngine | ||
| { | ||
| AutoShutdownEnabled = false | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we no longer need |
||
| }; | ||
| liveSpeechRequest = new SFSpeechAudioBufferRecognitionRequest() | ||
| { | ||
| ShouldReportPartialResults = options.ShouldReportPartialResults, | ||
|
|
@@ -59,38 +54,8 @@ Task InternalStartListening(SpeechToTextOptions options, CancellationToken token | |
| throw new Exception(error.LocalizedDescription); | ||
| } | ||
|
|
||
| var currentIndex = 0; | ||
| recognitionTask = speechRecognizer.GetRecognitionTask(liveSpeechRequest, (result, err) => | ||
| { | ||
| if (err is not null) | ||
| { | ||
| InternalStopListening(); | ||
| OnRecognitionResultCompleted(SpeechToTextResult.Failed(new Exception(err.LocalizedDescription))); | ||
| } | ||
| else | ||
| { | ||
| if (result.Final) | ||
| { | ||
| currentIndex = 0; | ||
| InternalStopListening(); | ||
| OnRecognitionResultCompleted(SpeechToTextResult.Success(result.BestTranscription.FormattedString)); | ||
| } | ||
| else | ||
| { | ||
| if (currentIndex <= 0) | ||
| { | ||
| OnSpeechToTextStateChanged(CurrentState); | ||
| } | ||
|
|
||
| for (var i = currentIndex; i < result.BestTranscription.Segments.Length; i++) | ||
| { | ||
| var s = result.BestTranscription.Segments[i].Substring; | ||
| currentIndex++; | ||
| OnRecognitionResultUpdated(s); | ||
| } | ||
| } | ||
| } | ||
| }); | ||
| InitSilenceTimer(options); | ||
| recognitionTask = CreateSpeechRecognizerTask(speechRecognizer, liveSpeechRequest); | ||
|
|
||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -35,6 +35,11 @@ public event EventHandler<SpeechToTextStateChangedEventArgs> StateChanged | |
| public async Task StartListenAsync(SpeechToTextOptions options, CancellationToken cancellationToken = default) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As CoPilot pointed out, we have a potential race condition here. Let's add a public sealed partial class OfflineSpeechToTextImplementation : ISpeechToText
{
readonly SemaphoreSlim startListeningSemaphoreSlim = new(1, 1);
public async Task StartListenAsync(SpeechToTextOptions options, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
await startListeningSemaphoreSlim.WaitAsync(cancellationToken);
try
{
if (CurrentState is not SpeechToTextState.Stopped)
{
return;
}
await InternalStartListening(options, cancellationToken);
}
finally
{
startListeningSemaphoreSlim.Release();
}
}
} |
||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
| if (CurrentState != SpeechToTextState.Stopped) | ||
| { | ||
| return; | ||
| } | ||
|
Comment on lines
+38
to
+41
|
||
|
|
||
| await InternalStartListening(options, cancellationToken); | ||
| } | ||
|
Comment on lines
35
to
44
|
||
|
|
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.