生成された音声へのデバイス プロファイルの使用

このページでは、Text-to-Speech によって作成された音声のデバイス プロファイルを選択する方法について説明します。

さまざまなタイプのハードウェアで再生するために、Text-to-Speech で生成された合成音声を最適化できます。たとえば、アプリが主に小型の「ウェアラブル」タイプのデバイスで動作する場合、小型のスピーカー専用に最適化された合成音声を Text-to-Speech API から作成できます。

複数のデバイス プロファイルを同じ合成音声に適用することもできます。Text-to-Speech API では、text:synthesize エンドポイントへのリクエストで指定された順序でデバイス プロファイルをオーディオに適用します。同じプロファイルを複数回適用すると、望ましくない結果が生じる可能性があるため、同じプロファイルを複数回指定することは避けてください。

音声プロファイルの使用は任意です。1 つ(または複数)を使用する場合、Text-to-Speech は合成後の音声結果にプロファイルを適用します。音声プロファイルを使用しない場合は、合成後の変更なしに音声結果を受け取ることができます。

複数のプロファイルから生成された音声の違いを聞き分けるには、以下の 2 つのクリップを比較してください。


例 1。handset-class-device プロファイルで生成された音声


例 2。telephony-class-application プロファイルで生成された音声

注: 各音声プロファイルは、音声効果の範囲を調整することによって、特定のデバイス向けに最適化されています。ただし、プロファイルの調整に使用されるデバイスのメーカーとモデルは、ユーザーの再生デバイスと完全には一致しない場合があります。アプリケーションに最適な音声出力を探すには、さまざまなプロファイルでテストする必要が生じる場合があります。

利用可能な音声プロファイル

次の表に、Text-to-Speech API で利用可能なデバイス プロファイルの ID と例を示します。

音声プロファイル ID 使用に適したデバイスの例
wearable-class-device スマートウォッチやその他のウェアラブル(Apple Watch、Wear OS watch など)
handset-class-device スマートフォン(Google Pixel、Samsung Galaxy、Apple iPhone など)
headphone-class-device オーディオ再生用のイヤフォンやヘッドフォン(Sennheiser ヘッドフォンなど)
small-bluetooth-speaker-class-device 小型の家庭用スピーカー(Google Home Mini など)
medium-bluetooth-speaker-class-device 家庭用スマート スピーカー(Google Home など)
large-home-entertainment-class-device 家庭用エンターテイメント システムやスマートテレビ(Google Home Max、LG TV など)
large-automotive-class-device 車載用スピーカー
telephony-class-application インタラクティブ音声レスポンス(IVR)システム

使用する音声プロファイルの指定

使用する音声プロファイルを指定するには、音声合成リクエストの effectsProfileId フィールドを設定します。

プロトコル

音声ファイルを生成するには、POST リクエストを作成して適切なリクエスト本文を指定します。次は、curl を使用した POST リクエストの例です。この例では、Google Cloud CLI を使用してリクエストのアクセス トークンを取得しています。gcloud CLI のインストール手順については、Text-to-Speech に対する認証を行うをご覧ください。

次の例は、text:synthesize エンドポイントにリクエストを送信する方法を示しています。

curl \
  -H "Authorization: Bearer "$(gcloud auth print-access-token) \
  -H "Content-Type: application/json; charset=utf-8" \
  --data "{
    'input':{
      'text':'This is a sentence that helps test how audio profiles can change the way Cloud Text-to-Speech sounds.'
    },
    'voice':{
      'languageCode':'en-us',
    },
    'audioConfig':{
      'audioEncoding':'LINEAR16',
      'effectsProfileId': ['telephony-class-application']
    }
  }" "https://texttospeech.googleapis.com/v1beta1/text:synthesize" > audio-profile.txt

リクエストが成功すると、Text-to-Speech API は合成された音声を、JSON 出力に含まれる base64 でエンコードされたデータとして返します。audio-profiles.txt ファイルの JSON 出力は、次のようになります。

{
  "audioContent": "//NExAASCCIIAAhEAGAAEMW4kAYPnwwIKw/BBTpwTvB+IAxIfghUfW.."
}

Cloud Text-to-Speech API の結果を MP3 音声ファイルにデコードするには、audio-profiles.txt ファイルと同じディレクトリから次のコマンドを実行します。

sed 's|audioContent| |' < audio-profile.txt > tmp-output.txt && \
tr -d '\n ":{}' < tmp-output.txt > tmp-output-2.txt && \
base64 tmp-output-2.txt --decode > audio-profile.wav && \
rm tmp-output*.txt

Go

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

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


import (
	"fmt"
	"io"
	"io/ioutil"

	"context"

	texttospeech "cloud.google.com/go/texttospeech/apiv1"
	"cloud.google.com/go/texttospeech/apiv1/texttospeechpb"
)

// audioProfile generates audio from text using a custom synthesizer like a telephone call.
func audioProfile(w io.Writer, text string, outputFile string) error {
	// text := "hello"
	// outputFile := "out.mp3"

	ctx := context.Background()

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

	req := &texttospeechpb.SynthesizeSpeechRequest{
		Input: &texttospeechpb.SynthesisInput{
			InputSource: &texttospeechpb.SynthesisInput_Text{Text: text},
		},
		Voice: &texttospeechpb.VoiceSelectionParams{LanguageCode: "en-US"},
		AudioConfig: &texttospeechpb.AudioConfig{
			AudioEncoding:    texttospeechpb.AudioEncoding_MP3,
			EffectsProfileId: []string{"telephony-class-application"},
		},
	}

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

	if err = ioutil.WriteFile(outputFile, resp.AudioContent, 0644); err != nil {
		return err
	}

	fmt.Fprintf(w, "Audio content written to file: %v\n", outputFile)

	return nil
}

Java

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

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

/**
 * Demonstrates using the Text to Speech client with audio profiles to synthesize text or ssml
 *
 * @param text the raw text to be synthesized. (e.g., "Hello there!")
 * @param effectsProfile audio profile to be used for synthesis. (e.g.,
 *     "telephony-class-application")
 * @throws Exception on TextToSpeechClient Errors.
 */
public static void synthesizeTextWithAudioProfile(String text, String effectsProfile)
    throws Exception {
  // Instantiates a client
  try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
    // Set the text input to be synthesized
    SynthesisInput input = SynthesisInput.newBuilder().setText(text).build();

    // Build the voice request
    VoiceSelectionParams voice =
        VoiceSelectionParams.newBuilder()
            .setLanguageCode("en-US") // languageCode = "en_us"
            .setSsmlGender(SsmlVoiceGender.FEMALE) // ssmlVoiceGender = SsmlVoiceGender.FEMALE
            .build();

    // Select the type of audio file you want returned and the audio profile
    AudioConfig audioConfig =
        AudioConfig.newBuilder()
            .setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
            .addEffectsProfileId(effectsProfile) // audio profile
            .build();

    // Perform the text-to-speech request
    SynthesizeSpeechResponse response =
        textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);

    // Get the audio contents from the response
    ByteString audioContents = response.getAudioContent();

    // Write the response to the output file.
    try (OutputStream out = new FileOutputStream("output.mp3")) {
      out.write(audioContents.toByteArray());
      System.out.println("Audio content written to file \"output.mp3\"");
    }
  }
}

Node.js

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

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


/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const text = 'Text you want to vocalize';
// const outputFile = 'YOUR_OUTPUT_FILE_LOCAtION;
// const languageCode = 'LANGUAGE_CODE_FOR_OUTPUT';
// const ssmlGender = 'SSML_GENDER_OF_SPEAKER';

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

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

async function synthesizeWithEffectsProfile() {
  // Add one or more effects profiles to array.
  // Refer to documentation for more details:
  // https://cloud.google.com/text-to-speech/docs/audio-profiles
  const effectsProfileId = ['telephony-class-application'];

  const request = {
    input: {text: text},
    voice: {languageCode: languageCode, ssmlGender: ssmlGender},
    audioConfig: {audioEncoding: 'MP3', effectsProfileId: effectsProfileId},
  };

  const [response] = await client.synthesizeSpeech(request);
  const writeFile = util.promisify(fs.writeFile);
  await writeFile(outputFile, response.audioContent, 'binary');
  console.log(`Audio content written to file: ${outputFile}`);
}

Python

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

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

def synthesize_text_with_audio_profile(text, output, effects_profile_id):
    """Synthesizes speech from the input string of text."""
    from google.cloud import texttospeech

    client = texttospeech.TextToSpeechClient()

    input_text = texttospeech.SynthesisInput(text=text)

    # Note: the voice can also be specified by name.
    # Names of voices can be retrieved with client.list_voices().
    voice = texttospeech.VoiceSelectionParams(language_code="en-US")

    # Note: you can pass in multiple effects_profile_id. They will be applied
    # in the same order they are provided.
    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.MP3,
        effects_profile_id=[effects_profile_id],
    )

    response = client.synthesize_speech(
        input=input_text, voice=voice, audio_config=audio_config
    )

    # The response's audio_content is binary.
    with open(output, "wb") as out:
        out.write(response.audio_content)
        print('Audio content written to file "%s"' % output)

その他の言語

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

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

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