C# 谷歌语音到文本API超时
我想知道是否有办法设置google speech to text API调用的超时。下面的文档提供了从wav文件获取测试的代码。但是,我需要的是能够设置此API调用的超时。我不想永远等待谷歌API的回应。在最大值时,我想等待5秒钟,如果在5秒钟内没有得到结果,我想抛出一个错误并继续执行C# 谷歌语音到文本API超时,c#,.net,google-speech-api,C#,.net,Google Speech Api,我想知道是否有办法设置google speech to text API调用的超时。下面的文档提供了从wav文件获取测试的代码。但是,我需要的是能够设置此API调用的超时。我不想永远等待谷歌API的回应。在最大值时,我想等待5秒钟,如果在5秒钟内没有得到结果,我想抛出一个错误并继续执行 static object SyncRecognize(string filePath) { var speech = SpeechClient.Create(); var response =
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();
}
}