xref: /aosp_15_r20/external/google-cloud-java/java-speech/.readme-partials.yaml (revision 55e87721aa1bc457b326496a7ca40f3ea1a63287)
1*55e87721SMatt Gilbridecustom_content: |
2*55e87721SMatt Gilbride  ### Recognizing speech
3*55e87721SMatt Gilbride  The following code sample shows how to recognize speech using an audio file from a Cloud Storage bucket as input.
4*55e87721SMatt Gilbride  First, add the following imports at the top of your file:
5*55e87721SMatt Gilbride
6*55e87721SMatt Gilbride  ```java
7*55e87721SMatt Gilbride  import com.google.cloud.speech.v1.SpeechClient;
8*55e87721SMatt Gilbride  import com.google.cloud.speech.v1.RecognitionAudio;
9*55e87721SMatt Gilbride  import com.google.cloud.speech.v1.RecognitionConfig;
10*55e87721SMatt Gilbride  import com.google.cloud.speech.v1.RecognitionConfig.AudioEncoding;
11*55e87721SMatt Gilbride  import com.google.cloud.speech.v1.RecognizeResponse;
12*55e87721SMatt Gilbride  ```
13*55e87721SMatt Gilbride  Then add the following code to do the speech recognization:
14*55e87721SMatt Gilbride  ```java
15*55e87721SMatt Gilbride   try (SpeechClient speechClient = SpeechClient.create()) {
16*55e87721SMatt Gilbride     RecognitionConfig.AudioEncoding encoding = RecognitionConfig.AudioEncoding.FLAC;
17*55e87721SMatt Gilbride     int sampleRateHertz = 44100;
18*55e87721SMatt Gilbride     String languageCode = "en-US";
19*55e87721SMatt Gilbride     RecognitionConfig config = RecognitionConfig.newBuilder()
20*55e87721SMatt Gilbride       .setEncoding(encoding)
21*55e87721SMatt Gilbride       .setSampleRateHertz(sampleRateHertz)
22*55e87721SMatt Gilbride       .setLanguageCode(languageCode)
23*55e87721SMatt Gilbride       .build();
24*55e87721SMatt Gilbride     String uri = "gs://bucket_name/file_name.flac";
25*55e87721SMatt Gilbride     RecognitionAudio audio = RecognitionAudio.newBuilder()
26*55e87721SMatt Gilbride       .setUri(uri)
27*55e87721SMatt Gilbride       .build();
28*55e87721SMatt Gilbride     RecognizeResponse response = speechClient.recognize(config, audio);
29*55e87721SMatt Gilbride   }
30*55e87721SMatt Gilbride  ```
31*55e87721SMatt Gilbride
32*55e87721SMatt Gilbride  #### Complete source code
33*55e87721SMatt Gilbride
34*55e87721SMatt Gilbride  In [RecognizeSpeech.java](https://github.com/googleapis/google-cloud-java/blob/master/google-cloud-examples/src/main/java/com/google/cloud/examples/speech/snippets/RecognizeSpeech.java) we put a quick start example, which shows how you can use Google Speech API to automatically recognize speech based on a local file.
35*55e87721SMatt Gilbride
36*55e87721SMatt Gilbride  For an example audio file, you can use the [audio.raw](https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/speech/cloud-client/resources/audio.raw) file from the samples repository.
37*55e87721SMatt Gilbride  Note, to play the file on Unix-like system you may use the following command: `play -t raw -r 16k -e signed -b 16 -c 1 audio.raw`