在產生的音訊使用裝置設定檔

此頁面說明如何為 Text-to-Speech 建立的音訊選取裝置設定檔。

您可以將 Text-to-Speech 產生的合成語音最佳化,以在不同類型的硬體上播放。舉例來說,如果您的應用程式主要是在較小型的「穿戴式」裝置上執行,則可以用 Text-to-Speech API 建立專為小型喇叭最佳化處理的合成語音。

您也可以將多個裝置設定檔套用到相同的合成語音。Text-to-Speech API 會依照向 text:synthesize 端點提出的要求中的順序,將裝置設定檔套用到音訊。請避免重複指定相同的設定檔,因為多次套用相同的設定檔,可能會產生不良結果。

音訊設定檔為選用功能。如果選擇使用一或多個設定檔, 「文字轉語音」就會將設定檔套用至合成語音結果。 如果您選擇不使用音訊設定檔,系統會直接提供語音結果,不會進行任何後續合成修改。

若想聽出不同設定檔產生的音訊之間的差異,請比較下面兩個剪輯。


範例 1:使用 handset-class-device 設定檔產生的音訊


範例 2:使用 telephony-class-application 設定檔產生的音訊

注意:每個音訊設定檔都調整過各種音訊效果,針對特定裝置進行了最佳化處理。然而,用來微調設定檔的裝置,其廠牌與型號未必完全與使用者的裝置相符。您可能需要使用不同的設定檔多加測試,找出最適合您應用程式的音效輸出效果。

可用的音訊設定檔

下表列出 Text-to-Speech API 可用的裝置設定檔 ID 和範例。

音訊設定檔 ID 適合用途
wearable-class-device 智慧型手錶及其他穿戴式裝置,例如 Apple Watch、Wear OS 手錶
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 要求並提供適當的要求主體。以下為使用 curlPOST 要求示例。這個範例會使用 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 會以 base64 編碼資料傳回合成的音訊,包含在 JSON 輸出中。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 Go API 參考說明文件

如要向 Text-to-Speech 服務驗證身分,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import (
	"fmt"
	"io"
	"os"

	"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 = os.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 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 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 Python API 參考說明文件

如要向 Text-to-Speech 服務驗證身分,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

    text = "hello"
    output = "output.mp3"
    effects_profile_id = "telephony-class-application"
    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 參考說明文件