テキスト ファイルから SSML を読み取る

テキスト ファイルから SSML を読み取ります。

コードサンプル

Go

Text-to-Speech 用のクライアント ライブラリをインストールして使用する方法については、Text-to-Speech クライアント ライブラリをご覧ください。詳細については、Text-to-Speech Go API のリファレンス ドキュメントをご覧ください。

Text-to-Speech で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境での認証情報の設定をご覧ください。


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

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

	ssml, err := ioutil.ReadFile(ssmlFile)
	if err != nil {
		return err
	}

	req := texttospeechpb.SynthesizeSpeechRequest{
		Input: &texttospeechpb.SynthesisInput{
			InputSource: &texttospeechpb.SynthesisInput_Ssml{Ssml: string(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

Text-to-Speech 用のクライアント ライブラリをインストールして使用する方法については、Text-to-Speech クライアント ライブラリをご覧ください。詳細については、Text-to-Speech Java API のリファレンス ドキュメントをご覧ください。

Text-to-Speech で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境での認証情報の設定をご覧ください。

/**
 * Demonstrates using the Text to Speech client to synthesize a text file or ssml file.
 *
 * @param ssmlFile the ssml document to be synthesized. (e.g., hello.ssml)
 * @throws Exception on TextToSpeechClient Errors.
 */
public static void synthesizeSsmlFile(String ssmlFile) throws Exception {
  // Instantiates a client
  try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
    // Read the file's contents
    String contents = new String(Files.readAllBytes(Paths.get(ssmlFile)));
    // Set the ssml input to be synthesized
    SynthesisInput input = SynthesisInput.newBuilder().setSsml(contents).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\"");
    }
  }
}

Node.js

Text-to-Speech 用のクライアント ライブラリをインストールして使用する方法については、Text-to-Speech クライアント ライブラリをご覧ください。詳細については、Text-to-Speech Node.js API のリファレンス ドキュメントをご覧ください。

Text-to-Speech で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境での認証情報の設定をご覧ください。

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 ssmlFile = 'Local path to SSML file, eg. input.ssml';
// const outputFile = 'Local path to save audio file to, e.g. output.mp3';

const request = {
  input: {ssml: fs.readFileSync(ssmlFile)},
  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}`);

PHP

Text-to-Speech 用のクライアント ライブラリをインストールして使用する方法については、Text-to-Speech クライアント ライブラリをご覧ください。

Text-to-Speech で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境での認証情報の設定をご覧ください。

use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
use Google\Cloud\TextToSpeech\V1\Client\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
use Google\Cloud\TextToSpeech\V1\SynthesizeSpeechRequest;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;

/**
 * @param string $path Path to file to synthesize
 */
function synthesize_ssml_file(string $path): void
{
    // create client object
    $client = new TextToSpeechClient();

    // get ssml from file
    $ssml = file_get_contents($path);
    $input_text = (new SynthesisInput())
        ->setSsml($ssml);

    // note: the voice can also be specified by name
    // names of voices can be retrieved with $client->listVoices()
    $voice = (new VoiceSelectionParams())
        ->setLanguageCode('en-US')
        ->setSsmlGender(SsmlVoiceGender::FEMALE);

    $audioConfig = (new AudioConfig())
        ->setAudioEncoding(AudioEncoding::MP3);
    $request = (new SynthesizeSpeechRequest())
        ->setInput($input_text)
        ->setVoice($voice)
        ->setAudioConfig($audioConfig);

    $response = $client->synthesizeSpeech($request);
    $audioContent = $response->getAudioContent();

    file_put_contents('output.mp3', $audioContent);
    print('Audio content written to "output.mp3"' . PHP_EOL);

    $client->close();
}

Python

Text-to-Speech 用のクライアント ライブラリをインストールして使用する方法については、Text-to-Speech クライアント ライブラリをご覧ください。詳細については、Text-to-Speech Python API のリファレンス ドキュメントをご覧ください。

Text-to-Speech で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境での認証情報の設定をご覧ください。

def synthesize_ssml_file(ssml_file):
    """Synthesizes speech from the input file of ssml.

    Note: ssml must be well-formed according to:
        https://www.w3.org/TR/speech-synthesis/
    """
    from google.cloud import texttospeech

    client = texttospeech.TextToSpeechClient()

    with open(ssml_file) as f:
        ssml = f.read()
        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", 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"')

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルを検索およびフィルタするには、Google Cloud のサンプル ブラウザをご覧ください。