短い音声ファイルの音声文字変換

このページでは、同期音声認識を使用して、短い音声ファイルをテキストに変換する方法を説明します。

同期音声認識は、短い音声(60 秒未満)で認識されたテキストを返します。60 秒を超える音声の音声認識リクエストを処理するには、非同期音声認識を使用します。

音声コンテンツは、ローカル ファイルから Speech-to-Text に直接送信できます。また、Speech-to-Text では Google Cloud Storage バケットに保存された音声コンテンツを処理できます。同期音声認識リクエストの制限については、割り当てと上限のページをご覧ください。

ローカル ファイルで同期音声認識を実行する

ローカル音声ファイルに対して、同期音声認識を実行する例を次に示します。

REST

詳細については、speech:recognize API エンドポイントをご覧ください。リクエスト本文の構成について詳しくは、RecognitionConfig のリファレンス ドキュメントをご覧ください。

リクエスト本文に含まれる音声コンテンツは、Base64 でエンコードされている必要があります。音声を Base64 でエンコードする方法について詳しくは、Base64 エンコード音声コンテンツをご覧ください。content フィールドの詳細については、RecognitionAudio をご覧ください。

リクエストのデータを使用する前に、次のように置き換えます。

  • LANGUAGE_CODE: 音声クリップで使用されている言語の BCP-47 コード。
  • ENCODING: 文字変換する音声のエンコード。
  • SAMPLE_RATE_HERTZ: 文字変換する音声のサンプルレート(ヘルツ単位)。
  • ENABLE_WORD_TIME_OFFSETS: 単語の開始時間と終了時間のオフセット(タイムスタンプ)を返す場合に、このフィールドを有効にします。
  • INPUT_AUDIO: 文字変換する音声データの Base64 エンコード文字列。
  • PROJECT_ID: Google Cloud プロジェクトの英数字の ID。

HTTP メソッドと URL:

POST https://speech.googleapis.com/v1/speech:recognize

リクエストの本文(JSON):

{
  "config": {
      "languageCode": "LANGUAGE_CODE",
      "encoding": "ENCODING",
      "sampleRateHertz": SAMPLE_RATE_HERTZ,
      "enableWordTimeOffsets": ENABLE_WORD_TIME_OFFSETS
  },
  "audio": {
    "content": "INPUT_AUDIO"
  }
}

リクエストを送信するには、次のいずれかのオプションを展開します。

次のような JSON レスポンスが返されます。

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "how old is the Brooklyn Bridge",
          "confidence": 0.98267895
        }
      ]
    }
  ]
}

gcloud

詳しくは、recognize コマンドをご覧ください。

ローカル ファイルに対して音声認識を実行するには、Google Cloud CLI を使用してファイルのローカル ファイル パスを渡し、音声認識を実行します。

gcloud ml speech recognize PATH-TO-LOCAL-FILE --language-code='en-US'

リクエストが成功すると、サーバーは JSON 形式のレスポンスを返します。

{
  "results": [
    {
      "alternatives": [
        {
          "confidence": 0.9840146,
          "transcript": "how old is the Brooklyn Bridge"
        }
      ]
    }
  ]
}

Go

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Go API リファレンス ドキュメントをご覧ください。

Speech-to-Text に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


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

	client, err := speech.NewClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	data, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}

	// Send the contents of the audio file with the encoding and
	// and sample rate information to be transcripted.
	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_Content{Content: data},
		},
	})

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

Java

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Java API リファレンス ドキュメントをご覧ください。

Speech-to-Text に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * Performs speech recognition on raw PCM audio and prints the transcription.
 *
 * @param fileName the path to a PCM audio file to transcribe.
 */
public static void syncRecognizeFile(String fileName) throws Exception {
  try (SpeechClient speech = SpeechClient.create()) {
    Path path = Paths.get(fileName);
    byte[] data = Files.readAllBytes(path);
    ByteString audioBytes = ByteString.copyFrom(data);

    // Configure request with local raw PCM audio
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.LINEAR16)
            .setLanguageCode("en-US")
            .setSampleRateHertz(16000)
            .build();
    RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(audioBytes).build();

    // Use blocking call to get audio transcript
    RecognizeResponse response = speech.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

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Node.js API リファレンス ドキュメントをご覧ください。

Speech-to-Text に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

// 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 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,
};
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

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Python API リファレンス ドキュメントをご覧ください。

Speech-to-Text に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import argparse

from google.cloud import speech

def transcribe_file(speech_file: str) -> speech.RecognizeResponse:
    """Transcribe the given audio file."""
    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",
    )

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

    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET の Speech-to-Text のリファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP の Speech-to-Text のリファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby の Speech-to-Text のリファレンス ドキュメントをご覧ください。

リモート ファイルで同期音声認識を実行する

Speech-to-Text API は、リクエストの本文で音声ファイルのコンテンツを送信しなくても、Google Cloud Storage にある音声ファイルに対して直接同期音声認識を実行できるようになっています。

Cloud Storage に保存されたファイルに対して同期音声認識を実行する例を次に示します。

REST

詳細については、speech:recognize API エンドポイントをご覧ください。リクエスト本文の構成について詳しくは、RecognitionConfig のリファレンス ドキュメントをご覧ください。

リクエスト本文に含まれる音声コンテンツは、Base64 でエンコードされている必要があります。音声を Base64 でエンコードする方法について詳しくは、Base64 エンコード音声コンテンツをご覧ください。content フィールドの詳細については、RecognitionAudio をご覧ください。

リクエストのデータを使用する前に、次のように置き換えます。

  • LANGUAGE_CODE: 音声クリップで使用されている言語の BCP-47 コード。
  • ENCODING: 文字変換する音声のエンコード。
  • SAMPLE_RATE_HERTZ: 文字変換する音声のサンプルレート(ヘルツ単位)。
  • ENABLE_WORD_TIME_OFFSETS: 単語の開始時間と終了時間のオフセット(タイムスタンプ)を返す場合に、このフィールドを有効にします。
  • STORAGE_BUCKET: Cloud Storage バケット。
  • INPUT_AUDIO: 音声文字変換する音声データファイル。
  • PROJECT_ID: Google Cloud プロジェクトの英数字の ID。

HTTP メソッドと URL:

POST https://speech.googleapis.com/v1/speech:recognize

リクエストの本文(JSON):

{
  "config": {
      "languageCode": "LANGUAGE_CODE",
      "encoding": "ENCODING",
      "sampleRateHertz": SAMPLE_RATE_HERTZ,
      "enableWordTimeOffsets": ENABLE_WORD_TIME_OFFSETS
  },
  "audio": {
    "uri": "gs://STORAGE_BUCKET/INPUT_AUDIO"
  }
}

リクエストを送信するには、次のいずれかのオプションを展開します。

次のような JSON レスポンスが返されます。

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "how old is the Brooklyn Bridge",
          "confidence": 0.98267895
        }
      ]
    }
  ]
}

gcloud

詳しくは、recognize コマンドをご覧ください。

ローカル ファイルに対して音声認識を実行するには、Google Cloud CLI を使用してファイルのローカル ファイル パスを渡し、音声認識を実行します。

gcloud ml speech recognize 'gs://cloud-samples-tests/speech/brooklyn.flac' \
--language-code='en-US'

リクエストが成功すると、サーバーは JSON 形式のレスポンスを返します。

{
  "results": [
    {
      "alternatives": [
        {
          "confidence": 0.9840146,
          "transcript": "how old is the Brooklyn Bridge"
        }
      ]
    }
  ]
}

Go

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Go API リファレンス ドキュメントをご覧ください。

Speech-to-Text に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


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

	client, err := speech.NewClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	// Send the request with the URI (gs://...)
	// and sample rate information to be transcripted.
	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: gcsURI},
		},
	})

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

Java

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Java API リファレンス ドキュメントをご覧ください。

Speech-to-Text に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * Performs speech recognition on remote FLAC file and prints the transcription.
 *
 * @param gcsUri the path to the remote FLAC audio file to transcribe.
 */
public static void syncRecognizeGcs(String gcsUri) throws Exception {
  // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
  try (SpeechClient speech = SpeechClient.create()) {
    // Builds the request for remote FLAC file
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.FLAC)
            .setLanguageCode("en-US")
            .setSampleRateHertz(16000)
            .build();
    RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

    // Use blocking call for getting audio transcript
    RecognizeResponse response = speech.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

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Node.js API リファレンス ドキュメントをご覧ください。

Speech-to-Text に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

// 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 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,
};
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

Speech-to-Text 用のクライアント ライブラリをインストールして使用する方法については、Speech-to-Text クライアント ライブラリをご覧ください。詳細については、Speech-to-Text の Python API リファレンス ドキュメントをご覧ください。

Speech-to-Text に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def transcribe_gcs(gcs_uri: str) -> speech.RecognizeResponse:
    """Transcribes the audio file specified by the gcs_uri."""
    from google.cloud import speech

    client = speech.SpeechClient()

    audio = speech.RecognitionAudio(uri=gcs_uri)
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.FLAC,
        sample_rate_hertz=16000,
        language_code="en-US",
    )

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

    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET の Speech-to-Text のリファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP の Speech-to-Text のリファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby の Speech-to-Text のリファレンス ドキュメントをご覧ください。