Bibliotecas cliente da API Speech-to-Text

Esta página mostra como começar a usar as bibliotecas cliente da Google Cloud para a API Speech-to-Text. As bibliotecas cliente facilitam o acesso às Google Cloud APIs a partir de um idioma suportado. Embora possa usar as Google Cloud APIs diretamente fazendo pedidos não processados ao servidor, as bibliotecas cliente oferecem simplificações que reduzem significativamente a quantidade de código que tem de escrever.

Leia mais acerca das bibliotecas cliente da Google Cloud e das bibliotecas cliente das APIs Google mais antigas em Bibliotecas cliente explicadas.

Instale a biblioteca de cliente

C#

Se estiver a usar o Visual Studio 2017 ou superior, abra a janela do gestor de pacotes NuGet e escreva o seguinte:

Install-Package Google.Apis

Se estiver a usar ferramentas da interface de linhas de comando do .NET Core para instalar as dependências, execute o seguinte comando:

dotnet add package Google.Apis

Para mais informações, consulte o artigo Configurar um ambiente de desenvolvimento C#.

Go

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

Para mais informações, consulte o artigo Configurar um ambiente de desenvolvimento 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.66.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.67.0'

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

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

If you're using Visual Studio Code, IntelliJ, or Eclipse, 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.

Para mais informações, consulte o artigo Configurar um ambiente de desenvolvimento Java.

Node.js

npm install @google-cloud/speech

Para mais informações, consulte o artigo Configurar um ambiente de desenvolvimento do Node.js.

PHP

composer require google/apiclient

Para mais informações, consulte o artigo Usar o PHP no Google Cloud.

Python

pip install --upgrade google-cloud-speech

Para mais informações, consulte o artigo Configurar um ambiente de desenvolvimento Python.

Ruby

gem install google-api-client

Para mais informações, consulte o artigo Configurar um ambiente de desenvolvimento Ruby.

Configure a autenticação

Para autenticar chamadas para Google Cloud APIs, as bibliotecas cliente suportam Credenciais padrão da aplicação (ADC); as bibliotecas procuram credenciais num conjunto de localizações definidas e usam essas credenciais para autenticar pedidos para a API. Com o ADC, pode disponibilizar credenciais à sua aplicação numa variedade de ambientes, como desenvolvimento local ou produção, sem ter de modificar o código da aplicação.

Para ambientes de produção, a forma como configura o ADC depende do serviço e do contexto. Para mais informações, consulte o artigo Configure as Credenciais padrão da aplicação.

Para um ambiente de desenvolvimento local, pode configurar o ADC com as credenciais associadas à sua Conta 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.

    É apresentado um ecrã de início de sessão. Depois de iniciar sessão, as suas credenciais são armazenadas no ficheiro de credenciais local usado pelo ADC.

Use a biblioteca de cliente

O exemplo seguinte mostra como usar a biblioteca cliente.

Go


// Sample speech-quickstart uses the Google Cloud Speech API to transcribe
// audio.
package main

import (
	"context"
	"fmt"
	"log"

	speech "cloud.google.com/go/speech/apiv1"
	"cloud.google.com/go/speech/apiv1/speechpb"
)

func main() {
	ctx := context.Background()

	// Creates a client.
	client, err := speech.NewClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer client.Close()

	// The path to the remote audio file to transcribe.
	fileURI := "gs://cloud-samples-data/speech/brooklyn_bridge.raw"

	// Detects speech in the audio file.
	resp, err := client.Recognize(ctx, &speechpb.RecognizeRequest{
		Config: &speechpb.RecognitionConfig{
			Encoding:        speechpb.RecognitionConfig_LINEAR16,
			SampleRateHertz: 16000,
			LanguageCode:    "en-US",
		},
		Audio: &speechpb.RecognitionAudio{
			AudioSource: &speechpb.RecognitionAudio_Uri{Uri: fileURI},
		},
	})
	if err != nil {
		log.Fatalf("failed to recognize: %v", err)
	}

	// Prints the results.
	for _, result := range resp.Results {
		for _, alt := range result.Alternatives {
			fmt.Printf("\"%v\" (confidence=%3f)\n", alt.Transcript, alt.Confidence)
		}
	}
}

Java

// Imports the Google Cloud client library
import com.google.cloud.speech.v1.RecognitionAudio;
import com.google.cloud.speech.v1.RecognitionConfig;
import com.google.cloud.speech.v1.RecognitionConfig.AudioEncoding;
import com.google.cloud.speech.v1.RecognizeResponse;
import com.google.cloud.speech.v1.SpeechClient;
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.SpeechRecognitionResult;
import java.util.List;

public class QuickstartSample {

  /** Demonstrates using the Speech API to transcribe an audio file. */
  public static void main(String... args) throws Exception {
    // Instantiates a client
    try (SpeechClient speechClient = SpeechClient.create()) {

      // The path to the audio file to transcribe
      String gcsUri = "gs://cloud-samples-data/speech/brooklyn_bridge.raw";

      // Builds the sync recognize request
      RecognitionConfig config =
          RecognitionConfig.newBuilder()
              .setEncoding(AudioEncoding.LINEAR16)
              .setSampleRateHertz(16000)
              .setLanguageCode("en-US")
              .build();
      RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

      // Performs speech recognition on the audio file
      RecognizeResponse response = speechClient.recognize(config, audio);
      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.
        SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
        System.out.printf("Transcription: %s%n", alternative.getTranscript());
      }
    }
  }
}

Node.js

// Imports the Google Cloud client library
const speech = require('@google-cloud/speech');

// Creates a client
const client = new speech.SpeechClient();

async function quickstart() {
  // The path to the remote LINEAR16 file
  const gcsUri = 'gs://cloud-samples-data/speech/brooklyn_bridge.raw';

  // The audio file's encoding, sample rate in hertz, and BCP-47 language code
  const audio = {
    uri: gcsUri,
  };
  const config = {
    encoding: 'LINEAR16',
    sampleRateHertz: 16000,
    languageCode: 'en-US',
  };
  const request = {
    audio: audio,
    config: config,
  };

  // Detects speech in the audio file
  const [response] = await client.recognize(request);
  const transcription = response.results
    .map(result => result.alternatives[0].transcript)
    .join('\n');
  console.log(`Transcription: ${transcription}`);
}
quickstart();

Python


# Imports the Google Cloud client library


from google.cloud import speech



def run_quickstart() -> speech.RecognizeResponse:
    # Instantiates a client
    client = speech.SpeechClient()

    # The name of the audio file to transcribe
    gcs_uri = "gs://cloud-samples-data/speech/brooklyn_bridge.raw"

    audio = speech.RecognitionAudio(uri=gcs_uri)

    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code="en-US",
    )

    # Detects speech in the audio file
    response = client.recognize(config=config, audio=audio)

    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")

Recursos adicionais

C#

A lista seguinte contém links para mais recursos relacionados com a biblioteca cliente para C#:

Go

A lista seguinte contém links para mais recursos relacionados com a biblioteca de cliente para Go:

Java

A lista seguinte contém links para mais recursos relacionados com a biblioteca cliente para Java:

Node.js

A lista seguinte contém links para mais recursos relacionados com a biblioteca de cliente para Node.js:

PHP

A lista seguinte contém links para mais recursos relacionados com a biblioteca de cliente para PHP:

Python

A lista seguinte contém links para mais recursos relacionados com a biblioteca cliente para Python:

Ruby

A lista seguinte contém links para mais recursos relacionados com a biblioteca de cliente para Ruby: