Library klien Speech-to-Text

}

Halaman ini menjelaskan cara mulai menggunakan Library Klien Cloud untuk Speech-to-Text API. Library klien mempermudah akses Google Cloud API dari bahasa yang didukung. Meskipun Anda dapat langsung menggunakan Google Cloud API dengan membuat permintaan mentah ke server, library klien memberikan penyederhanaan yang secara signifikan mengurangi jumlah kode yang perlu Anda tulis.

Baca lebih lanjut tentang Library Klien Cloud dan Library Klien Google API lama di Penjelasan library klien.

Menginstal library klien

C#

Install-Package Google.Cloud.Speech.V2

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan C#.

Go

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

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan 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.40.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

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

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

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

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

libraryDependencies += "com.google.cloud" % "google-cloud-speech" % "4.39.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.

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Java.

Node.js

npm install --save @google-cloud/speech

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Node.js.

PHP

composer require google/cloud/speech

Untuk informasi selengkapnya, lihat Menggunakan PHP di Google Cloud.

Python

pip install --upgrade google-cloud-speech

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Python.

Ruby

gem install google-cloud-speech

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Ruby.

Menyiapkan autentikasi

Untuk mengautentikasi panggilan ke Google Cloud API, library klien mendukung Kredensial Default Aplikasi (ADC); library akan mencari kredensial di sekumpulan lokasi yang ditentukan dan menggunakan kredensial tersebut untuk mengautentikasi permintaan ke API. Dengan ADC, Anda dapat membuat kredensial tersedia untuk aplikasi di berbagai lingkungan, seperti produksi atau pengembangan lokal, tanpa perlu mengubah kode aplikasi.

Untuk lingkungan produksi, cara Anda menyiapkan ADC bergantung pada layanan dan konteks. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan Kredensial Default Aplikasi.

Untuk lingkungan pengembangan lokal, Anda dapat menyiapkan ADC dengan kredensial yang terkait dengan Akun Google Anda:

  1. Instal dan lakukan inisialisasi gcloud CLI.

    Saat melakukan inisialisasi gcloud CLI, pastikan untuk menentukan project Google Cloud yang izinnya Anda miliki untuk mengakses resource yang dibutuhkan aplikasi Anda.

  2. Buat file kredensial Anda:

    gcloud auth application-default login

    Layar login akan muncul. Setelah Anda login, kredensial Anda akan disimpan di file kredensial lokal yang digunakan oleh ADC.

Menggunakan library klien

Contoh berikut menunjukkan cara menggunakan library klien.

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 = result.getAlternativesList().get(0);
          System.out.printf("Transcription: %s%n", alternative.getTranscript());
        }
      }
    }
  }
}

Python

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech

def quickstart_v2(
    project_id: str,
    audio_file: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribe an audio file."""
    # Instantiates a client
    client = SpeechClient()

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        content = f.read()

    config = cloud_speech.RecognitionConfig(
        auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
        language_codes=["en-US"],
        model="long",
    )

    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{project_id}/locations/global/recognizers/_",
        config=config,
        content=content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

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

    return response

Referensi tambahan

C#

Daftar berikut berisi link ke resource lainnya yang terkait dengan library klien untuk C#:

Go

Daftar berikut berisi link ke resource lainnya terkait library klien untuk Go:

Java

Daftar berikut berisi link ke resource lainnya terkait library klien untuk Java:

Node.js

Daftar berikut berisi link ke resource lainnya yang terkait dengan library klien untuk Node.js:

PHP

Daftar berikut berisi link ke resource lainnya terkait library klien untuk PHP:

Python

Daftar berikut berisi link ke lebih banyak referensi terkait library klien untuk Python:

Ruby

Daftar berikut berisi link ke resource lainnya yang terkait dengan library klien untuk Ruby: