How to wait for speech recognition callback

Brian Erickson 346 Reputation points
2021-03-15T03:18:51.773+00:00

I've got the Android speech recognition stuff working well but have a question.

I've got a method called StartListening(). It's starts the speech recognition mechanism and when the OnResult call back gets fired the caller is notified via an event notification.

Now, what I'd like is a method call Listen. It should return a string consisting of the words spoken by the user. The best I've been able to come with is:

      async public Task<string> Listen()
      {
         Words = null;
         GlobalVariables.SpokenWords.SpokenWordsEvent += SpokenWordsEventHandler;
         Device.BeginInvokeOnMainThread(() =>
         {
            StartListening();
         });

         while (Words == null)
            await Task.Delay(100);

         GlobalVariables.SpokenWords.SpokenWordsEvent -= SpokenWordsEventHandler;

         return (Words);
      }

It does work but is very ugly. I'm sure there's a better way but I don't see it...any help? It would be ideal if it was not marked async...

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,325 questions
0 comments No comments
{count} votes

Accepted answer
  1. Cole Xia (Shanghai Wicresoft Co,.Ltd.) 6,751 Reputation points
    2021-03-15T05:46:13.277+00:00

    Hello,

    Welcome to Microsoft Q&A!

    Take a look at TaskCompletionSource , It enables the creation of a task that can be handed out to consumers.

    Sample
       public Task<string> MyTask()  
       {  
         
           var tcs = new TaskCompletionSource<string>();  
         
           {  
               //OnResult call back  
               tcs.SetResult(Words);  
           }  
         
           return tcs.Task;  
         
       }  
    

    BTW , I would suggest you use official sample for SpeechToText.

    We could handle the callback in OnActivityResult method in activity.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful