Créer des fichiers audio vocaux

Text-to-Speech vous permet de convertir des mots et des phrases en données audio de voix humaines naturelles encodées en base64. Vous pouvez ensuite convertir les données audio en un fichier audio lisible, comme un fichier MP3, en décodant les données base64. L'API Text-to-Speech accepte les entrées sous forme de texte brut ou dans le langage de balisage de synthèse vocale (SSML).

Ce document explique comment créer un fichier audio à partir d'une entrée de texte ou SSML à l'aide de Text-to-Speech. Si les concepts tels que la synthèse vocale ou SSML ne vous sont pas familiers, vous pouvez également consulter l'article Concepts de base de Text-to-Speech.

Ces exemples nécessitent que vous ayez installé et initialisé Google Cloud CLI. Pour en savoir plus sur la configuration de gcloud CLI, consultez la page S'authentifier auprès de TTS.

Convertir du texte en contenus audio vocaux synthétiques

Les exemples de code suivants montrent comment convertir une chaîne en données audio.

Vous pouvez configurer la sortie de la synthèse vocale de différentes manières, par exemple en sélectionnant une voix unique ou en modulant la hauteur vocale, le volume, la vitesse d'élocution et le taux d'échantillonnage de la sortie.

Protocole

Reportez-vous au point de terminaison text:synthesize de l'API pour obtenir des informations complètes.

Pour synthétiser des contenus audio à partir d'un texte, envoyez une requête HTTP POST au point de terminaison text:synthesize. Dans le corps de la requête POST, spécifiez le type de voix à synthétiser dans la section de configuration voice, le texte à synthétiser dans le champ text de la section input et le type de contenus audio à créer dans la section audioConfig.

L'extrait de code suivant envoie une requête de synthèse au point de terminaison text:synthesize, puis enregistre les résultats dans un fichier nommé synthesize-text.txt. Remplacez PROJECT_ID par l'ID de votre projet.

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

L'API Text-to-Speech renvoie l'audio synthétisé sous forme de données encodées en base64 dans la sortie JSON. La sortie JSON du fichier synthesize-text.txt est semblable à l'extrait de code suivant.

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

Pour décoder les résultats de l'API Text-to-Speech sous forme de fichier audio MP3, exécutez la commande suivante à partir du répertoire dans lequel se trouve le fichier 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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Text-to-Speech, consultez la page Bibliothèques clientes Text-to-Speech. Pour en savoir plus, consultez la documentation de référence de l'API Text-to-Speech en langage Go.

Pour vous authentifier auprès de Text-to-Speech, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


// 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 = ioutil.WriteFile(outputFile, resp.AudioContent, 0644)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Audio content written to file: %v\n", outputFile)
	return nil
}

Java

Pour savoir comment installer et utiliser la bibliothèque cliente Text-to-Speech, consultez la page Bibliothèques clientes Text-to-Speech. Pour en savoir plus, consultez la documentation de référence de l'API Text-to-Speech en langage Java.

Pour vous authentifier auprès de Text-to-Speech, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour savoir comment installer et utiliser la bibliothèque cliente Text-to-Speech, consultez la page Bibliothèques clientes Text-to-Speech. Pour en savoir plus, consultez la documentation de référence de l'API Text-to-Speech en langage Node.js.

Pour vous authentifier auprès de Text-to-Speech, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour savoir comment installer et utiliser la bibliothèque cliente Text-to-Speech, consultez la page Bibliothèques clientes Text-to-Speech. Pour en savoir plus, consultez la documentation de référence de l'API Text-to-Speech en langage Python.

Pour vous authentifier auprès de Text-to-Speech, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

def synthesize_text(text):
    """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",
        name="en-US-Standard-C",
        ssml_gender=texttospeech.SsmlVoiceGender.FEMALE,
    )

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

    response = client.synthesize_speech(
        request={"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"')

Langages supplémentaires

C# : Veuillez suivre les Instructions de configuration de C# sur la page des bibliothèques clientes, puis consultez la pageDocumentation de référence sur Text-to-Speech pour .NET.

PHP : Veuillez suivre les Instructions de configuration de PHP sur la page des bibliothèques clientes, puis consultez la page Documentation de référence sur Text-to-Speech pour PHP.

Ruby : Veuillez suivre les Instructions de configuration de Ruby sur la page des bibliothèques clientes, puis consultez la page Documentation de référence sur Text-to-Speech pour Ruby.

Convertir des données SSML en contenus audio vocaux synthétiques

L'utilisation du langage SSML dans la requête de synthèse audio peut produire des contenus audio plus proches de la voix humaine naturelle. En particulier, SSML vous permet de contrôler plus précisément la manière dont la sortie audio représente les pauses dans le discours, ou dont le locuteur prononce les dates, les heures, les acronymes et les abréviations.

Pour en savoir plus sur les éléments SSML acceptés par l'API Text-to-Speech, consultez la documentation de référence SSML.

Protocole

Reportez-vous au point de terminaison text:synthesize de l'API pour obtenir des informations complètes.

Pour synthétiser des contenus audio à partir de données SSML, envoyez une requête HTTP POST au point de terminaison text:synthesize. Dans le corps de la requête POST, spécifiez le type de voix à synthétiser dans la section de configuration voice, les données SSML à synthétiser dans le champ ssml de la section input et le type de contenus audio à créer dans la section audioConfig.

L'extrait de code suivant envoie une requête de synthèse au point de terminaison text:synthesize, puis enregistre les résultats dans un fichier nommé synthesize-ssml.txt. Remplacez PROJECT_ID par l'ID de votre projet.

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

L'API Text-to-Speech renvoie l'audio synthétisé sous forme de données encodées en base64 dans la sortie JSON. La sortie JSON du fichier synthesize-ssml.txt est semblable à l'extrait de code suivant.

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

Pour décoder les résultats de l'API Text-to-Speech sous forme de fichier audio MP3, exécutez la commande suivante à partir du répertoire dans lequel se trouve le fichier 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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Text-to-Speech, consultez la page Bibliothèques clientes Text-to-Speech. Pour en savoir plus, consultez la documentation de référence de l'API Text-to-Speech en langage Go.

Pour vous authentifier auprès de Text-to-Speech, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


// 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 = ioutil.WriteFile(outputFile, resp.AudioContent, 0644)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Audio content written to file: %v\n", outputFile)
	return nil
}

Java

Pour savoir comment installer et utiliser la bibliothèque cliente Text-to-Speech, consultez la page Bibliothèques clientes Text-to-Speech. Pour en savoir plus, consultez la documentation de référence de l'API Text-to-Speech en langage Java.

Pour vous authentifier auprès de Text-to-Speech, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour savoir comment installer et utiliser la bibliothèque cliente Text-to-Speech, consultez la page Bibliothèques clientes Text-to-Speech. Pour en savoir plus, consultez la documentation de référence de l'API Text-to-Speech en langage Node.js.

Pour vous authentifier auprès de Text-to-Speech, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour savoir comment installer et utiliser la bibliothèque cliente Text-to-Speech, consultez la page Bibliothèques clientes Text-to-Speech. Pour en savoir plus, consultez la documentation de référence de l'API Text-to-Speech en langage Python.

Pour vous authentifier auprès de Text-to-Speech, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

def synthesize_ssml(ssml):
    """Synthesizes speech from the input string of ssml.

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

    Example: <speak>Hello there.</speak>
    """
    from google.cloud import texttospeech

    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"')

Langages supplémentaires

C# : Veuillez suivre les Instructions de configuration de C# sur la page des bibliothèques clientes, puis consultez la pageDocumentation de référence sur Text-to-Speech pour .NET.

PHP : Veuillez suivre les Instructions de configuration de PHP sur la page des bibliothèques clientes, puis consultez la page Documentation de référence sur Text-to-Speech pour PHP.

Ruby : Veuillez suivre les Instructions de configuration de Ruby sur la page des bibliothèques clientes, puis consultez la page Documentation de référence sur Text-to-Speech pour Ruby.

Faites l'essai

Si vous débutez sur Google Cloud, créez un compte pour évaluer les performances de Text-to-Speech en conditions réelles. Les nouveaux clients bénéficient également de 300 $ de crédits offerts pour exécuter, tester et déployer des charges de travail.

Profiter d'un essai gratuit de Text-to-Speech