יצירת קובצי אודיו של קול

שירות Cloud Text-to-Speech מאפשר לכם להמיר מילים ומשפטים לנתוני אודיו בקידוד base64 של דיבור אנושי טבעי. לאחר מכן אפשר להמיר את נתוני האודיו לקובץ אודיו שניתן להפעלה, כמו MP3, על ידי פענוח נתוני ה-Base64. ה-API של Cloud Text-to-Speech מקבל קלט כטקסט גולמי או כ-Speech Synthesis Markup Language (SSML).

במסמך הזה מוסבר איך ליצור קובץ אודיו מטקסט או מקלט SSML באמצעות Cloud TTS. אם אתם לא מכירים מושגים כמו סינתזת דיבור או SSML, תוכלו לעיין גם במאמר בנושא היסודות של Cloud TTS.

כדי להשתמש בדוגמאות האלה, צריך להתקין ולהפעיל את Google Cloud CLI. למידע על הגדרת ה-CLI של gcloud, אפשר לעיין במאמר בנושא אימות ל-Cloud TTS.

המרת טקסט לאודיו של קול סינתטי

בדוגמאות הקוד הבאות אפשר לראות איך ממירים מחרוזת לנתוני אודיו.

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

פרוטוקול

פרטים נוספים זמינים בנקודת קצה ל-API של text:synthesize.

כדי לבצע סינתזה של אודיו מטקסט, שולחים בקשת HTTP POST לנקודת הקצה text:synthesize. בגוף בקשת ה-POST, מציינים את סוג הקול לסינתזה בקטע voice configuration, מציינים את הטקסט לסינתזה בשדה text בקטע input, ומציינים את סוג האודיו ליצירה בקטע audioConfig.

קטע הקוד הבא שולח בקשת סינתזה לנקודת הקצה text:synthesize ושומר את התוצאות בקובץ בשם synthesize-text.txt. מחליפים את PROJECT_ID במזהה הפרויקט.

curl -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "x-goog-user-project: <var>PROJECT_ID</var>" \
  -H "Content-Type: application/json; charset=utf-8" \
  --data "{
    'input':{
      'text':'Android is a mobile operating system developed by Google,
         based on the Linux kernel and designed primarily for
         touchscreen mobile devices such as smartphones and tablets.'
    },
    'voice':{
      'languageCode':'en-gb',
      'name':'en-GB-Standard-A',
      'ssmlGender':'FEMALE'
    },
    'audioConfig':{
      'audioEncoding':'MP3'
    }
  }" "https://texttospeech.googleapis.com/v1/text:synthesize" > synthesize-text.txt

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

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

כדי לפענח את התוצאות מ-Cloud Text-to-Speech API כקובץ אודיו MP3, מריצים את הפקודה הבאה מאותה ספרייה שבה נמצא קובץ synthesize-text.txt.

cat synthesize-text.txt | grep 'audioContent' | \
sed 's|audioContent| |' | tr -d '\n ":{},' > tmp.txt && \
base64 tmp.txt --decode > synthesize-text-audio.mp3 && \
rm tmp.txt

Go

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

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


// SynthesizeText synthesizes plain text and saves the output to outputFile.
func SynthesizeText(w io.Writer, text, outputFile string) error {
	ctx := context.Background()

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

	req := texttospeechpb.SynthesizeSpeechRequest{
		Input: &texttospeechpb.SynthesisInput{
			InputSource: &texttospeechpb.SynthesisInput_Text{Text: text},
		},
		// Note: the voice can also be specified by name.
		// Names of voices can be retrieved with client.ListVoices().
		Voice: &texttospeechpb.VoiceSelectionParams{
			LanguageCode: "en-US",
			SsmlGender:   texttospeechpb.SsmlVoiceGender_FEMALE,
		},
		AudioConfig: &texttospeechpb.AudioConfig{
			AudioEncoding: texttospeechpb.AudioEncoding_MP3,
		},
	}

	resp, err := client.SynthesizeSpeech(ctx, &req)
	if err != nil {
		return err
	}

	err = os.WriteFile(outputFile, resp.AudioContent, 0644)
	if 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 to synthesize text or ssml.
 *
 * @param text the raw text to be synthesized. (e.g., "Hello there!")
 * @throws Exception on TextToSpeechClient Errors.
 */
public static ByteString synthesizeText(String text) 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
    AudioConfig audioConfig =
        AudioConfig.newBuilder()
            .setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
            .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. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

const textToSpeech = require('@google-cloud/text-to-speech');
const fs = require('fs');
const util = require('util');

const client = new textToSpeech.TextToSpeechClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const text = 'Text to synthesize, eg. hello';
// const outputFile = 'Local path to save audio file to, e.g. output.mp3';

const request = {
  input: {text: text},
  voice: {languageCode: 'en-US', ssmlGender: 'FEMALE'},
  audioConfig: {audioEncoding: 'MP3'},
};
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():
    """Synthesizes speech from the input string of text."""
    from google.cloud import texttospeech

    text = "Hello there."
    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",
        name="en-US-Chirp3-HD-Charon",
    )

    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.MP3
    )

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

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

שפות נוספות

C#: צריך לפעול לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה של Cloud TTS ל-‎ .NET.

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

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

המרת SSML לאודיו של קול מסונתז

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

לפרטים נוספים על רכיבי SSML שנתמכים על ידי Cloud Text-to-Speech API, אפשר לעיין במאמר בנושא SSML.

פרוטוקול

פרטים נוספים זמינים בנקודת קצה ל-API של text:synthesize.

כדי לבצע סינתזה של אודיו מ-SSML, שולחים בקשת HTTP POST לנקודת הקצה text:synthesize. בגוף בקשת ה-POST, מציינים את סוג הקול לסינתזה בקטע ההגדרה voice, מציינים את ה-SSML לסינתזה בשדה ssml בקטע input, ומציינים את סוג האודיו ליצירה בקטע audioConfig.

קטע הקוד הבא שולח בקשת סינתזה לנקודת הקצה text:synthesize ושומר את התוצאות בקובץ בשם synthesize-ssml.txt. מחליפים את PROJECT_ID במזהה הפרויקט.

curl -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "x-goog-user-project: <var>PROJECT_ID</var>" \
  -H "Content-Type: application/json; charset=utf-8" --data "{
    'input':{
     'ssml':'<speak>The <say-as interpret-as=\"characters\">SSML</say-as> standard
          is defined by the <sub alias=\"World Wide Web Consortium\">W3C</sub>.</speak>'
    },
    'voice':{
      'languageCode':'en-us',
      'name':'en-US-Standard-B',
      'ssmlGender':'MALE'
    },
    'audioConfig':{
      'audioEncoding':'MP3'
    }
  }" "https://texttospeech.googleapis.com/v1/text:synthesize" > synthesize-ssml.txt

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

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

כדי לפענח את התוצאות מ-Text-to-Speech API כקובץ אודיו MP3, מריצים את הפקודה הבאה מאותה ספרייה שבה נמצא קובץ synthesize-ssml.txt.

cat synthesize-ssml.txt | grep 'audioContent' | \
sed 's|audioContent| |' | tr -d '\n ":{},' > tmp.txt && \
base64 tmp.txt --decode > synthesize-ssml-audio.mp3 && \
rm tmp.txt

Go

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

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


// SynthesizeSSML synthesizes ssml and saves the output to outputFile.
//
// ssml must be well-formed according to:
//
//	https://www.w3.org/TR/speech-synthesis/
//
// Example: <speak>Hello there.</speak>
func SynthesizeSSML(w io.Writer, ssml, outputFile string) error {
	ctx := context.Background()

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

	req := texttospeechpb.SynthesizeSpeechRequest{
		Input: &texttospeechpb.SynthesisInput{
			InputSource: &texttospeechpb.SynthesisInput_Ssml{Ssml: ssml},
		},
		// Note: the voice can also be specified by name.
		// Names of voices can be retrieved with client.ListVoices().
		Voice: &texttospeechpb.VoiceSelectionParams{
			LanguageCode: "en-US",
			SsmlGender:   texttospeechpb.SsmlVoiceGender_FEMALE,
		},
		AudioConfig: &texttospeechpb.AudioConfig{
			AudioEncoding: texttospeechpb.AudioEncoding_MP3,
		},
	}

	resp, err := client.SynthesizeSpeech(ctx, &req)
	if err != nil {
		return err
	}

	err = os.WriteFile(outputFile, resp.AudioContent, 0644)
	if 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 to synthesize text or ssml.
 *
 * <p>Note: ssml must be well-formed according to: (https://www.w3.org/TR/speech-synthesis/
 * Example: <speak>Hello there.</speak>
 *
 * @param ssml the ssml document to be synthesized. (e.g., "<?xml...")
 * @throws Exception on TextToSpeechClient Errors.
 */
public static ByteString synthesizeSsml(String ssml) throws Exception {
  // Instantiates a client
  try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
    // Set the ssml input to be synthesized
    SynthesisInput input = SynthesisInput.newBuilder().setSsml(ssml).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
    AudioConfig audioConfig =
        AudioConfig.newBuilder()
            .setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
            .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. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

const textToSpeech = require('@google-cloud/text-to-speech');
const fs = require('fs');
const util = require('util');

const client = new textToSpeech.TextToSpeechClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const ssml = '<speak>Hello there.</speak>';
// const outputFile = 'Local path to save audio file to, e.g. output.mp3';

const request = {
  input: {ssml: ssml},
  voice: {languageCode: 'en-US', ssmlGender: 'FEMALE'},
  audioConfig: {audioEncoding: 'MP3'},
};

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_ssml():
    """Synthesizes speech from the input string of ssml.

    Note: ssml must be well-formed according to:
        https://www.w3.org/TR/speech-synthesis/

    """
    from google.cloud import texttospeech

    ssml = "<speak>Hello there.</speak>"
    client = texttospeech.TextToSpeechClient()

    input_text = texttospeech.SynthesisInput(ssml=ssml)

    # 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",
        name="en-US-Standard-C",
        ssml_gender=texttospeech.SsmlVoiceGender.FEMALE,
    )

    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.MP3
    )

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

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

שפות נוספות

C#: צריך לפעול לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה של Cloud TTS ל-‎ .NET.

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

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

נסו בעצמכם

אנחנו ממליצים למשתמשים חדשים ב-Google Cloud ליצור חשבון כדי שיוכלו להעריך את הביצועים של Cloud TTS בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300 $להרצה, לבדיקה ולפריסה של עומסי העבודה.

להתנסות ב-Cloud TTS בחינם