谷歌语音到文本API超时



我想知道是否有办法在google语音到文本API调用上设置超时。下面的文档是从wav文件中获取测试的代码。然而,我需要的是能够设置这个API调用的超时。我不想永远等待谷歌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;
}

如何中止长时间运行的方法?此处找到原始代码

线程将在您设定的时间内运行,然后中止。您可以将异常处理或记录器放入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();
}
}

最新更新