Bibliothèques clientes Cloud Speech-to-Text

Cette page explique comment débuter avec les bibliothèques clientes Cloud pour l'API Cloud Speech-to-Text. Les bibliothèques clientes facilitent l'accès aux APIGoogle Cloud à l'aide d'un langage compatible. Bien que vous puissiez utiliser directement les APIGoogle Cloud en envoyant des requêtes brutes au serveur, les bibliothèques clientes vous simplifient la tâche en réduisent considérablement la quantité de code à écrire.

Pour en savoir plus sur les bibliothèques clientes Cloud et les anciennes bibliothèques clientes pour les API Google, consultez Présentation des bibliothèques clientes.

Installer la bibliothèque cliente

C#

Install-Package Google.Cloud.Speech.V2

Pour en savoir plus, consultez la page Configurer un environnement de développement C#.

Go

go get cloud.google.com/go/speech/apiv2

Pour en savoir plus, consultez Configurer un environnement de développement Go.

Java

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.72.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-speech</artifactId>
  </dependency>
</dependencies>

If you are using Gradle, add the following to your dependencies:

implementation 'com.google.cloud:google-cloud-speech:4.75.0'

If you are using sbt, add the following to your dependencies:

libraryDependencies += "com.google.cloud" % "google-cloud-speech" % "4.75.0"

If you're using Visual Studio Code or IntelliJ, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Pour en savoir plus, consultez Configurer un environnement de développement Java.

Node.js

npm install @google-cloud/speech

Pour en savoir plus, consultez Configurer un environnement de développement Node.js.

PHP

composer require google/cloud/speech

Pour en savoir plus, consultez la page Utiliser PHP sur Google Cloud.

Python

pip install --upgrade google-cloud-speech

Pour en savoir plus, consultez la page Configurer un environnement de développement Python.

Ruby

gem install google-cloud-speech

Pour en savoir plus, consultez Configurer un environnement de développement Ruby.

Configurer l'authentification

Pour authentifier les appels aux API Google Cloud , les bibliothèques clientes utilisent le service Identifiants par défaut de l'application (ADC). Les bibliothèques recherchent des identifiants dans un ensemble d'emplacements définis et les utilisent pour authentifier les requêtes adressées à l'API. Grâce à ADC, vous pouvez mettre des identifiants à disposition de votre application dans divers environnements, tels que l'environnement de développement ou de production local, sans avoir à modifier le code de votre application.

Pour les environnements de production, la façon de configurer ADC dépend du service et du contexte. Pour en savoir plus, consultez Configurer le service Identifiants par défaut de l'application.

Pour un environnement de développement local, vous pouvez configurer ADC avec les identifiants associés à votre compte Google :

  1. Install the Google Cloud CLI. After installation, initialize the Google Cloud CLI by running the following command:

    gcloud init

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  2. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Un écran de connexion s'affiche. Une fois que vous êtes connecté, vos identifiants sont stockés dans le fichier d'identifiants local utilisé par ADC.

Utiliser la bibliothèque cliente

L'exemple suivant vous montre comment utiliser la bibliothèque cliente.

Java

// Imports the Google Cloud client library
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.speech.v2.AutoDetectDecodingConfig;
import com.google.cloud.speech.v2.CreateRecognizerRequest;
import com.google.cloud.speech.v2.OperationMetadata;
import com.google.cloud.speech.v2.RecognitionConfig;
import com.google.cloud.speech.v2.RecognizeRequest;
import com.google.cloud.speech.v2.RecognizeResponse;
import com.google.cloud.speech.v2.Recognizer;
import com.google.cloud.speech.v2.SpeechClient;
import com.google.cloud.speech.v2.SpeechRecognitionAlternative;
import com.google.cloud.speech.v2.SpeechRecognitionResult;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class QuickstartSampleV2 {

  public static void main(String[] args) throws IOException, ExecutionException,
      InterruptedException {
    String projectId = "my-project-id";
    String filePath = "path/to/audioFile.raw";
    String recognizerId = "my-recognizer-id";
    quickstartSampleV2(projectId, filePath, recognizerId);
  }

  public static void quickstartSampleV2(String projectId, String filePath, String recognizerId)
      throws IOException, ExecutionException, InterruptedException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (SpeechClient speechClient = SpeechClient.create()) {
      Path path = Paths.get(filePath);
      byte[] data = Files.readAllBytes(path);
      ByteString audioBytes = ByteString.copyFrom(data);

      String parent = String.format("projects/%s/locations/global", projectId);

      // First, create a recognizer
      Recognizer recognizer = Recognizer.newBuilder()
          .setModel("latest_long")
          .addLanguageCodes("en-US")
          .build();

      CreateRecognizerRequest createRecognizerRequest = CreateRecognizerRequest.newBuilder()
          .setParent(parent)
          .setRecognizerId(recognizerId)
          .setRecognizer(recognizer)
          .build();

      OperationFuture<Recognizer, OperationMetadata> operationFuture =
          speechClient.createRecognizerAsync(createRecognizerRequest);
      recognizer = operationFuture.get();

      // Next, create the transcription request
      RecognitionConfig recognitionConfig = RecognitionConfig.newBuilder()
          .setAutoDecodingConfig(AutoDetectDecodingConfig.newBuilder().build())
          .build();

      RecognizeRequest request = RecognizeRequest.newBuilder()
          .setConfig(recognitionConfig)
          .setRecognizer(recognizer.getName())
          .setContent(audioBytes)
          .build();

      RecognizeResponse response = speechClient.recognize(request);
      List<SpeechRecognitionResult> results = response.getResultsList();

      for (SpeechRecognitionResult result : results) {
        // There can be several alternative transcripts for a given chunk of speech. Just use the
        // first (most likely) one here.
        if (result.getAlternativesCount() > 0) {
          SpeechRecognitionAlternative alternative =