Search code examples
c#.netgoogle-speech-api

Google speech to text API Timeout


I would like to know if there is a way to set Timeout on the google speech to text API call. From the documentation below is the code to get the test from a wav file. However what i need is be able to set the timeout for this API call. I don't want to wait forever for the response from Google API. At max i want to wait for 5 seconds, and if i don't get the result under 5 seconds i want to throw an error and move on with further execution.

static object SyncRecognize(string filePath)
{
    var speech = SpeechClient.Create();
    var response = speech.Recognize(new RecognitionConfig()
    {
        Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
        SampleRateHertz = 16000,
        LanguageCode = "en",
    }, RecognitionAudio.FromFile(filePath));
    foreach (var result in response.Results)
    {
        foreach (var alternative in result.Alternatives)
        {
            Console.WriteLine(alternative.Transcript);
        }
    }
    return 0;
}

Solution

  • How to abort a long running method? Original code found here

    The thread will run for your set time then abort you can put your exception handling or logger in the if statement. The long running method is only for demonstration purposes.

       class Program
        {
            static void Main(string[] args)
            {
    
                //Method will keep on printing forever as true is true trying to simulate a long runnning method
                void LongRunningMethod()
                {
                    while (true)
                    {
                        Console.WriteLine("Test");
                    }
                }
    
    
                //New thread runs for set amount of time then aborts the operation after the time in this case 1 second.
               void StartThread()
                {
                    Thread t = new Thread(LongRunningMethod);
                    t.Start();
                    if (!t.Join(1000)) // give the operation 1s to complete
                    {
                        Console.WriteLine("Aborted");
                        // the thread did not complete on its own, so we will abort it now
                        t.Abort();
    
                    }
                }
    
                //Calling the start thread method.
                StartThread();
    
            }
        }