diff --git a/speech/snippets/src/main/java/com/example/speech/Recognize.java b/speech/snippets/src/main/java/com/example/speech/Recognize.java index 629974ad415..51586d9ca8a 100644 --- a/speech/snippets/src/main/java/com/example/speech/Recognize.java +++ b/speech/snippets/src/main/java/com/example/speech/Recognize.java @@ -17,6 +17,9 @@ package com.example.speech; import com.google.api.gax.longrunning.OperationFuture; +import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.retrying.TimedRetryAlgorithm; import com.google.api.gax.rpc.ApiStreamObserver; import com.google.api.gax.rpc.BidiStreamingCallable; import com.google.api.gax.rpc.ClientStream; @@ -31,6 +34,7 @@ import com.google.cloud.speech.v1.SpeechClient; import com.google.cloud.speech.v1.SpeechRecognitionAlternative; import com.google.cloud.speech.v1.SpeechRecognitionResult; +import com.google.cloud.speech.v1.SpeechSettings; import com.google.cloud.speech.v1.StreamingRecognitionConfig; import com.google.cloud.speech.v1.StreamingRecognitionResult; import com.google.cloud.speech.v1.StreamingRecognizeRequest; @@ -50,6 +54,7 @@ import javax.sound.sampled.DataLine; import javax.sound.sampled.DataLine.Info; import javax.sound.sampled.TargetDataLine; +import org.threeten.bp.Duration; public class Recognize { @@ -331,8 +336,22 @@ public static void asyncRecognizeWords(String gcsUri) throws Exception { * @param gcsUri the path to the remote LINEAR16 audio file to transcribe. */ public static void asyncRecognizeGcs(String gcsUri) throws Exception { + // Configure polling algorithm + SpeechSettings.Builder speechSettings = SpeechSettings.newBuilder(); + TimedRetryAlgorithm timedRetryAlgorithm = OperationTimedPollAlgorithm.create( + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(500L)) + .setRetryDelayMultiplier(1.5) + .setMaxRetryDelay(Duration.ofMillis(5000L)) + .setInitialRpcTimeout(Duration.ZERO) // ignored + .setRpcTimeoutMultiplier(1.0) // ignored + .setMaxRpcTimeout(Duration.ZERO) // ignored + .setTotalTimeout(Duration.ofHours(24L)) // set polling timeout to 24 hours + .build()); + speechSettings.longRunningRecognizeOperationSettings().setPollingAlgorithm(timedRetryAlgorithm); + // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS - try (SpeechClient speech = SpeechClient.create()) { + try (SpeechClient speech = SpeechClient.create(speechSettings.build())) { // Configure remote file request for FLAC RecognitionConfig config =