שימוש בפרופילי מכשירים לאודיו שנוצר

בדף הזה מוסבר איך לבחור פרופיל מכשיר לאודיו שנוצר על ידי Cloud Text-to-Speech.

אתם יכולים לבצע אופטימיזציה של הדיבור הסינתטי שנוצר על ידי Cloud Text-to-Speech, כדי להפעיל אותו בסוגים שונים של חומרה. לדוגמה, אם האפליקציה פועלת בעיקר במכשירים קטנים יותר, כמו מכשירים לבישים, אפשר ליצור דיבור סינתטי באמצעות Cloud Text-to-Speech API, שמותאם במיוחד לרמקולים קטנים יותר.

אפשר גם להחיל כמה פרופילים של מכשירים על אותו דיבור מסונתז. ‫Cloud Text-to-Speech API מחיל פרופילי מכשירים על האודיו לפי הסדר שצוין בבקשה לנקודת הקצה (endpoint) text:synthesize. אל תציינו את אותו פרופיל יותר מפעם אחת, כי אם תפעילו את אותו פרופיל כמה פעמים, יכול להיות שתקבלו תוצאות לא רצויות.

השימוש בפרופילי אודיו הוא אופציונלי. אם תבחרו להשתמש בפרופיל אחד (או יותר), Cloud Text-to-Speech יחיל את הפרופילים על תוצאות הדיבור לאחר ההמרה. אם תבחרו לא להשתמש בפרופיל אודיו, תקבלו את תוצאות הדיבור ללא שינויים לאחר הסינתזה.

כדי לשמוע את ההבדל בין אודיו שנוצר מפרופילים שונים, השוו בין שני הקליפים הבאים.


דוגמה 1. האודיו נוצר באמצעות פרופיל handset-class-device


דוגמה 2. האודיו נוצר באמצעות פרופיל telephony-class-application

הערה: כל פרופיל אודיו עבר אופטימיזציה למכשיר ספציפי באמצעות התאמה של מגוון אפקטים קוליים. עם זאת, יכול להיות שהיצרן והדגם של המכשיר שבו השתמשתם כדי לכוונן את הפרופיל לא תואמים בדיוק למכשירי ההפעלה של המשתמשים. יכול להיות שתצטרכו לנסות פרופילים שונים כדי למצוא את פלט הצליל הטוב ביותר לאפליקציה שלכם.

פרופילי אודיו זמינים

בטבלה הבאה מפורטים המזהים והדוגמאות של פרופילי המכשירים שאפשר להשתמש בהם ב-Cloud Text-to-Speech API.

מזהה פרופיל האודיו מותאם ל-
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 ומספקים את גוף הבקשה המתאים. בדוגמה הבאה מוצגת בקשת POST באמצעות curl. בדוגמה הזו, משתמשים ב-Google Cloud CLI כדי לאחזר אסימון גישה לבקשה. במאמר אימות ל-Cloud TTS מוסבר איך מתקינים את ה-CLI של gcloud.

בדוגמה הבאה אפשר לראות איך שולחים בקשה לנקודת הקצה (endpoint) 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

אם הבקשה תתבצע בהצלחה, Cloud Text-to-Speech API יחזיר את האודיו המסונתז כנתונים בקידוד base64 שכלולים בפלט ה-JSON. פלט ה-JSON בקובץ audio-profiles.txt נראה כך:

{
  "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

במאמר ספריות הלקוח של Cloud TTS מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Cloud TTS. למידע נוסף, קראו את מאמרי העזרה של Cloud TTS Go API.

כדי לבצע אימות ב-Cloud TTS, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


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

במאמר ספריות הלקוח של Cloud TTS מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Cloud TTS. למידע נוסף, קראו את מאמרי העזרה של Cloud TTS Java API.

כדי לבצע אימות ב-Cloud TTS, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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 ByteString 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\"");
      return audioContents;
    }
  }
}

Node.js

במאמר ספריות הלקוח של Cloud TTS מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Cloud TTS. למידע נוסף, קראו את מאמרי העזרה של Cloud TTS Node.js API.

כדי לבצע אימות ב-Cloud TTS, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


/**
 * 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

במאמר ספריות הלקוח של Cloud TTS מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Cloud TTS. למידע נוסף, קראו את מאמרי העזרה של Cloud TTS Python API.

כדי לבצע אימות ב-Cloud TTS, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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# ‎ בדף ספריות הלקוח, ואז עיינו במאמרי העזרה של Cloud TTS ל-‎ .NET.

‫PHP: פועלים לפי הוראות ההגדרה של PHP בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Cloud TTS ל-PHP.

‫Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Cloud TTS ל-Ruby.