我想知道是否可以在Google语音到文本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;
}
答案 0 :(得分: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();
}
}