Transcribe audio from a video file using Speech-to-Text


Tutorial ini menunjukkan cara mentranskripsikan trek audio dari file video menggunakan Speech-to-Text.

File audio dapat berasal dari berbagai sumber yang berbeda. Data audio dapat berasal dari ponsel (seperti pesan suara) atau soundtrack yang disertakan dalam file video.

Speech-to-Text dapat menggunakan salah satu dari beberapa model machine learning untuk mentranskripsikan file audio Anda, agar cocok dengan sumber asli audio. Anda bisa mendapatkan hasil transkripsi ucapan yang lebih baik dengan menentukan sumber audio asli. Hal ini memungkinkan Speech-to-Text memproses file audio Anda menggunakan model machine learning yang dilatih untuk data yang mirip dengan file audio Anda.

Tujuan

  • Kirim permintaan transkripsi audio untuk file video ke Speech-to-Text.

Biaya

Dalam dokumen ini, Anda menggunakan komponen Google Cloud yang dapat ditagih berikut:

  • Speech-to-Text

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga. Pengguna baru Google Cloud mungkin memenuhi syarat untuk mendapatkan uji coba gratis.

Sebelum memulai

Tutorial ini memiliki beberapa prasyarat:

Menyiapkan data audio

Sebelum dapat mentranskripsikan audio dari video, Anda harus mengekstrak data dari file video. Setelah mengekstrak data audio, Anda harus menyimpannya dalam bucket Cloud Storage atau mengonversinya ke encoding base64.

Mengekstrak data audio

Anda dapat menggunakan alat konversi file apa pun yang menangani file audio dan video, seperti FFmpeg.

Gunakan cuplikan kode di bawah untuk mengonversi file video menjadi file audio menggunakan ffmpeg.

ffmpeg -i video-input-file audio-output-file

Menyimpan atau mengonversi data audio

Anda dapat mentranskripsikan file audio yang disimpan di komputer lokal atau di bucket Cloud Storage.

Gunakan perintah berikut untuk mengupload file audio Anda ke bucket Cloud Storage yang ada menggunakan alat gsutil.

gsutil cp audio-output-file storage-bucket-uri

Jika Anda menggunakan file lokal dan berencana mengirim permintaan menggunakan alat curl dari command line, Anda harus mengonversi file audio menjadi data yang dienkode base64 terlebih dahulu.

Gunakan perintah berikut untuk mengonversi file audio menjadi file teks.

base64 audio-output-file -w 0 > audio-data-text

Mengirim permintaan transkripsi

Gunakan kode berikut untuk mengirim permintaan transkripsi ke Speech-to-Text.

Permintaan file lokal

Protokol

Lihat endpoint speech:recognize API untuk detail selengkapnya.

Untuk melakukan pengenalan ucapan sinkron, buat permintaan POST dan berikan isi permintaan yang sesuai. Berikut ini contoh permintaan POST yang menggunakan curl. Contoh ini menggunakan Google Cloud CLI untuk membuat token akses. Untuk mengetahui petunjuk cara menginstal gcloud CLI, lihat quickstart.

curl -s -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    https://speech.googleapis.com/v1/speech:recognize \
    --data '{
    "config": {
        "encoding": "LINEAR16",
        "sampleRateHertz": 16000,
        "languageCode": "en-US",
        "model": "video"
    },
    "audio": {
        "uri": "gs://cloud-samples-tests/speech/Google_Gnome.wav"
    }
}'

Lihat dokumentasi referensi RecognitionConfig untuk mengetahui informasi selengkapnya tentang cara mengonfigurasi isi permintaan.

Jika permintaan berhasil, server akan menampilkan kode status HTTP 200 OK dan respons dalam format JSON:

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "OK Google stream stranger things from
            Netflix to my TV okay stranger things from
            Netflix playing on TV from the people that brought you
            Google home comes the next evolution of the smart home
            and it's just outside your window me Google know hi
            how can I help okay no what's the weather like outside
            the weather outside is sunny and 76 degrees he's right
            okay no turn on the hose I'm holding sure okay no I'm can
            I eat this lemon tree leaf yes what about this Daisy yes
            but I wouldn't recommend it but I could eat it okay
            Nomad milk to my shopping list I'm sorry that sounds like
            an indoor request I keep doing that sorry you do keep
            doing that okay no is this compost really we're all
            compost if you think about it pretty much everything is
            made up of organic matter and will return",
          "confidence": 0.9251011
        }
      ]
    }
  ]
}

Go

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Speech-to-Text, lihat Library klien Speech-to-Text. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Speech-to-Text.

Untuk mengautentikasi ke Speech-to-Text, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


func modelSelection(w io.Writer, path string) error {
	ctx := context.Background()

	client, err := speech.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	// path = "../testdata/Google_Gnome.wav"
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return fmt.Errorf("ReadFile: %w", err)
	}

	req := &speechpb.RecognizeRequest{
		Config: &speechpb.RecognitionConfig{
			Encoding:        speechpb.RecognitionConfig_LINEAR16,
			SampleRateHertz: 16000,
			LanguageCode:    "en-US",
			Model:           "video",
		},
		Audio: &speechpb.RecognitionAudio{
			AudioSource: &speechpb.RecognitionAudio_Content{Content: data},
		},
	}

	resp, err := client.Recognize(ctx, req)
	if err != nil {
		return fmt.Errorf("Recognize: %w", err)
	}

	for i, result := range resp.Results {
		fmt.Fprintf(w, "%s\n", strings.Repeat("-", 20))
		fmt.Fprintf(w, "Result %d\n", i+1)
		for j, alternative := range result.Alternatives {
			fmt.Fprintf(w, "Alternative %d: %s\n", j+1, alternative.Transcript)
		}
	}
	return nil
}

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Speech-to-Text, lihat Library klien Speech-to-Text. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Speech-to-Text.

Untuk mengautentikasi ke Speech-to-Text, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * Performs transcription of the given audio file synchronously with the selected model.
 *
 * @param fileName the path to a audio file to transcribe
 */
public static void transcribeModelSelection(String fileName) throws Exception {
  Path path = Paths.get(fileName);
  byte[] content = Files.readAllBytes(path);

  try (SpeechClient speech = SpeechClient.create()) {
    // Configure request with video media type
    RecognitionConfig recConfig =
        RecognitionConfig.newBuilder()
            // encoding may either be omitted or must match the value in the file header
            .setEncoding(AudioEncoding.LINEAR16)
            .setLanguageCode("en-US")
            // sample rate hertz may be either be omitted or must match the value in the file
            // header
            .setSampleRateHertz(16000)
            .setModel("video")
            .build();

    RecognitionAudio recognitionAudio =
        RecognitionAudio.newBuilder().setContent(ByteString.copyFrom(content)).build();

    RecognizeResponse recognizeResponse = speech.recognize(recConfig, recognitionAudio);
    // Just print the first result here.
    SpeechRecognitionResult result = recognizeResponse.getResultsList().get(0);
    // 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("Transcript : %s\n", alternative.getTranscript());
  }
}

Node.js

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Speech-to-Text, lihat Library klien Speech-to-Text. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Speech-to-Text.

Untuk mengautentikasi ke Speech-to-Text, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

// Imports the Google Cloud client library for Beta API
/**
 * TODO(developer): Update client library import to use new
 * version of API when desired features become available
 */
const speech = require('@google-cloud/speech').v1p1beta1;
const fs = require('fs');

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const filename = 'Local path to audio file, e.g. /path/to/audio.raw';
// const model = 'Model to use, e.g. phone_call, video, default';
// const encoding = 'Encoding of the audio file, e.g. LINEAR16';
// const sampleRateHertz = 16000;
// const languageCode = 'BCP-47 language code, e.g. en-US';

const config = {
  encoding: encoding,
  sampleRateHertz: sampleRateHertz,
  languageCode: languageCode,
  model: model,
};
const audio = {
  content: fs.readFileSync(filename).toString('base64'),
};

const request = {
  config: config,
  audio: audio,
};

// 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);

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Speech-to-Text, lihat Library klien Speech-to-Text. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Speech-to-Text.

Untuk mengautentikasi ke Speech-to-Text, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

def transcribe_model_selection(
    speech_file: str,
    model: str,
) -> speech.RecognizeResponse:
    """Transcribe the given audio file synchronously with
    the selected model."""
    client = speech.SpeechClient()

    with open(speech_file, "rb") as audio_file:
        content = audio_file.read()

    audio = speech.RecognitionAudio(content=content)

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

    response = client.recognize(config=config, audio=audio)

    for i, result in enumerate(response.results):
        alternative = result.alternatives[0]
        print("-" * 20)
        print(f"First alternative of result {i}")
        print(f"Transcript: {alternative.transcript}")

    return response

Bahasa tambahan

C# : Ikuti Petunjuk penyiapan C# di halaman library klien, lalu buka Dokumentasi referensi Speech-to-Text untuk .NET.

PHP : Ikuti Petunjuk penyiapan PHP di halaman library klien, lalu buka Dokumentasi referensi Speech-to-Text untuk PHP.

Ruby: Ikuti Petunjuk penyiapan Ruby di halaman library klien, lalu buka Dokumentasi referensi Speech-to-Text untuk Ruby.

Permintaan file jarak jauh

Go

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Speech-to-Text, lihat Library klien Speech-to-Text. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Speech-to-Text.

Untuk mengautentikasi ke Speech-to-Text, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import (
	"context"
	"fmt"
	"io"
	"strings"

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

// transcribe_model_selection_gcs Transcribes the given audio file asynchronously with
// the selected model.
func transcribe_model_selection_gcs(w io.Writer, gcsUri string, model string) error {
	// Google Cloud Storage URI pointing to the audio content.
	// gcsUri := "gs://bucket-name/path_to_audio_file"

	// The speech recognition model to use
	// See, https://cloud.google.com/speech-to-text/docs/speech-to-text-requests#select-model
	// model := "default"
	ctx := context.Background()

	client, err := speech.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	audio := &speechpb.RecognitionAudio{
		AudioSource: &speechpb.RecognitionAudio_Uri{Uri: gcsUri},
	}

	recognitionConfig := &speechpb.RecognitionConfig{
		Encoding:        speechpb.RecognitionConfig_LINEAR16,
		SampleRateHertz: 16000,
		LanguageCode:    "en-US",
		Model:           model,
	}

	longRunningRecognizeRequest := &speechpb.LongRunningRecognizeRequest{
		Config: recognitionConfig,
		Audio:  audio,
	}

	operation, err := client.LongRunningRecognize(ctx, longRunningRecognizeRequest)
	if err != nil {
		return fmt.Errorf("error running recognize %v", err)
	}

	response, err := operation.Wait(ctx)
	if err != nil {
		return err
	}
	for i, result := range response.Results {
		alternative := result.Alternatives[0]
		fmt.Fprintf(w, "%s\n", strings.Repeat("-", 20))
		fmt.Fprintf(w, "First alternative of result %d", i)
		fmt.Fprintf(w, "Transcript: %s", alternative.Transcript)
	}
	return nil
}

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Speech-to-Text, lihat Library klien Speech-to-Text. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Speech-to-Text.

Untuk mengautentikasi ke Speech-to-Text, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * Performs transcription of the remote audio file asynchronously with the selected model.
 *
 * @param gcsUri the path to the remote audio file to transcribe.
 */
public static void transcribeModelSelectionGcs(String gcsUri) throws Exception {
  try (SpeechClient speech = SpeechClient.create()) {

    // Configure request with video media type
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            // encoding may either be omitted or must match the value in the file header
            .setEncoding(AudioEncoding.LINEAR16)
            .setLanguageCode("en-US")
            // sample rate hertz may be either be omitted or must match the value in the file
            // header
            .setSampleRateHertz(16000)
            .setModel("video")
            .build();

    RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

    // Use non-blocking call for getting file transcription
    OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response =
        speech.longRunningRecognizeAsync(config, audio);

    while (!response.isDone()) {
      System.out.println("Waiting for response...");
      Thread.sleep(10000);
    }

    List<SpeechRecognitionResult> results = response.get().getResultsList();

    // Just print the first result here.
    SpeechRecognitionResult result = results.get(0);
    // 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("Transcript : %s\n", alternative.getTranscript());
  }
}

Node.js

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Speech-to-Text, lihat Library klien Speech-to-Text. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Speech-to-Text.

Untuk mengautentikasi ke Speech-to-Text, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

// Imports the Google Cloud client library for Beta API
/**
 * TODO(developer): Update client library import to use new
 * version of API when desired features become available
 */
const speech = require('@google-cloud/speech').v1p1beta1;

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const gcsUri = 'gs://my-bucket/audio.raw';
// const model = 'Model to use, e.g. phone_call, video, default';
// const encoding = 'Encoding of the audio file, e.g. LINEAR16';
// const sampleRateHertz = 16000;
// const languageCode = 'BCP-47 language code, e.g. en-US';

const config = {
  encoding: encoding,
  sampleRateHertz: sampleRateHertz,
  languageCode: languageCode,
  model: model,
};
const audio = {
  uri: gcsUri,
};

const request = {
  config: config,
  audio: audio,
};

// 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);

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Speech-to-Text, lihat Library klien Speech-to-Text. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Speech-to-Text.

Untuk mengautentikasi ke Speech-to-Text, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

def transcribe_model_selection_gcs(
    gcs_uri: str,
    model: str,
) -> speech.RecognizeResponse:
    """Transcribe the given audio file asynchronously with
    the selected model."""
    from google.cloud import speech

    client = speech.SpeechClient()

    audio = speech.RecognitionAudio(uri=gcs_uri)

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

    operation = client.long_running_recognize(config=config, audio=audio)

    print("Waiting for operation to complete...")
    response = operation.result(timeout=90)

    for i, result in enumerate(response.results):
        alternative = result.alternatives[0]
        print("-" * 20)
        print(f"First alternative of result {i}")
        print(f"Transcript: {alternative.transcript}")

    return response

Bahasa tambahan

C# : Ikuti Petunjuk penyiapan C# di halaman library klien, lalu buka Dokumentasi referensi Speech-to-Text untuk .NET.

PHP : Ikuti Petunjuk penyiapan PHP di halaman library klien, lalu buka Dokumentasi referensi Speech-to-Text untuk PHP.

Ruby: Ikuti Petunjuk penyiapan Ruby di halaman library klien, lalu buka Dokumentasi referensi Speech-to-Text untuk Ruby.

Pembersihan

Agar tidak perlu membayar biaya pada akun Google Cloud Anda untuk resource yang digunakan dalam tutorial ini, hapus project yang berisi resource tersebut, atau simpan project dan hapus setiap resource.

Menghapus project

Cara termudah untuk menghilangkan penagihan adalah dengan menghapus project yang Anda buat untuk tutorial.

Untuk menghapus project:

  1. Di konsol Google Cloud, buka halaman Manage resource.

    Buka Manage resource

  2. Pada daftar project, pilih project yang ingin Anda hapus, lalu klik Delete.
  3. Pada dialog, ketik project ID, lalu klik Shut down untuk menghapus project.

Menghapus instance

Untuk menghapus instance Compute Engine:

  1. Di konsol Google Cloud, buka halaman Instance VM.

    Buka VM instances

  2. Pilih kotak centang untuk instance yang ingin Anda hapus.
  3. Untuk menghapus instance, klik Tindakan lainnya, klik Hapus, lalu ikuti petunjuknya.

Menghapus aturan firewall untuk jaringan default

Untuk menghapus aturan firewall:

  1. Di Konsol Google Cloud, buka halaman Firewall.

    Buka Firewall

  2. Centang kotak untuk aturan firewall yang ingin Anda hapus.
  3. Untuk menghapus aturan firewall, klik Hapus.

Langkah selanjutnya

Cobalah sendiri

Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa Speech-to-Text dalam skenario dunia nyata. Pelanggan baru mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.

Coba Speech-to-Text gratis