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

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

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

אפשר גם להחיל כמה פרופילי מכשירים על אותו דיבור סינתטי. ממשק Cloud Text-to-Speech API מחיל פרופילים של מכשירים על האודיו לפי הסדר שצוין בבקשה לנקודת הקצה 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 כדי לאחזר אסימון גישה לבקשה. הוראות להתקנת ה-CLI של gcloud מופיעות במאמר אימות ל-Cloud TTS.

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

מידע על התקנת ספריית הלקוח של 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.