1414 * limitations under the License.
1515 */
1616
17-
1817package com .example .speech ;
1918
2019import com .google .cloud .speech .v2 .AutoDetectDecodingConfig ;
3130import java .nio .file .Paths ;
3231import java .util .List ;
3332
34-
3533public class TranscribeFileV2 {
3634 public static void main (String [] args ) throws IOException {
3735 String recognizerName = "projects/[PROJECT_ID]/locations/global/recognizers/[RECOGNIZER_ID]" ;
@@ -52,24 +50,28 @@ public static void transcribeFileV2(String recognizerName, String audioFilePath)
5250 ByteString audioBytes = ByteString .copyFrom (data );
5351
5452 // Create the recognition request
55- RecognitionConfig recognitionConfig = RecognitionConfig .newBuilder ()
56- .setAutoDecodingConfig (AutoDetectDecodingConfig .newBuilder ().build ())
57- .build ();
58-
59- RecognizeRequest request = RecognizeRequest .newBuilder ()
60- .setConfig (recognitionConfig )
61- .setRecognizer (recognizerName )
62- .setContent (audioBytes )
63- .build ();
64-
53+ RecognitionConfig recognitionConfig =
54+ RecognitionConfig .newBuilder ()
55+ .setAutoDecodingConfig (AutoDetectDecodingConfig .newBuilder ().build ())
56+ .build ();
57+
58+ RecognizeRequest request =
59+ RecognizeRequest .newBuilder ()
60+ .setConfig (recognitionConfig )
61+ .setRecognizer (recognizerName )
62+ .setContent (audioBytes )
63+ .build ();
64+
6565 RecognizeResponse response = speechClient .recognize (request );
6666 List <SpeechRecognitionResult > results = response .getResultsList ();
6767
6868 for (SpeechRecognitionResult result : results ) {
6969 // There can be several alternative transcripts for a given chunk of speech. Just use the
7070 // first (most likely) one here.
71- SpeechRecognitionAlternative alternative = result .getAlternativesList ().get (0 );
72- System .out .printf ("Transcription: %s%n" , alternative .getTranscript ());
71+ if (result .getAlternativesCount () > 0 ) {
72+ SpeechRecognitionAlternative alternative = result .getAlternativesList ().get (0 );
73+ System .out .printf ("Transcription: %s%n" , alternative .getTranscript ());
74+ }
7375 }
7476 }
7577 }
0 commit comments