Speech-to-Text Client Libraries

}

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#

Jika Anda menggunakan Visual Studio 2017 atau versi yang lebih baru, buka jendela pengelola paket nuget dan ketikkan berikut ini:

Install-Package Google.Apis

Jika Anda menggunakan alat antarmuka command line .NET Core untuk menginstal dependensi, jalankan perintah berikut:

dotnet add package Google.Apis

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan C#.

Go

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

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.37.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.37.0'

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

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

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-api-client

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.

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}")

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: