【问题标题】:Google speech to text API TimeoutGoogle 语音转文本 API 超时
【发布时间】:2018-11-06 14:35:46
【问题描述】:

我想知道是否有办法在谷歌语音到文本 API 调用上设置超时。下面的文档是从 wav 文件中获取测试的代码。但是我需要的是能够为这个 API 调用设置超时。我不想永远等待来自 Google API 的响应。最多我想等待 5 秒,如果我在 5 秒内没有得到结果,我想抛出一个错误并继续执行。

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;
}

【问题讨论】:

    标签: c# .net google-speech-api


    【解决方案1】:

    How to abort a long running method? 在此处找到原始代码

    线程将在您设定的时间内运行,然后中止,您可以将异常处理或记录器放在 if 语句中。长时间运行方法仅用于演示目的。

       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();
    
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多