생성된 오디오에 기기 프로필 사용

이 페이지에서는 Text-to-Speech에서 만든 오디오의 기기 프로필을 선택하는 방법을 설명합니다.

다양한 유형의 하드웨어에서 재생되도록 Text-to-Speech로 생성된 합성 음성을 최적화할 수 있습니다. 예를 들어 앱이 주로 소형 '웨어러블' 유형의 기기에서 실행되는 경우 특별히 소형 스피커에 최적화된 Text-to-Speech API로 합성 음성을 만들 수 있습니다.

동일한 합성 음성에 여러 기기 프로필을 적용할 수도 있습니다. Text-to-Speech API는 text:synthesize 엔드포인트에 대한 요청에 지정된 순서대로 기기 프로필을 오디오에 적용합니다. 동일한 프로필을 여러 번 적용하면 원하지 않는 결과가 발생할 수 있으므로 동일한 프로필을 두 번 이상 지정하지 마세요.

오디오 프로필 사용은 선택사항입니다. 하나 이상의 Text-to-Speech를 사용할 경우에는 Text-to-Speech가 게시물이 합성된 음성 결과에 프로필을 적용합니다. 오디오 프로필을 사용하지 않도록 선택한 경우에는 게시물 합성 수정 없이 음성 결과를 받게 됩니다.

서로 다른 프로필에서 생성된 오디오의 차이를 확인하려면 아래 두 클립을 비교해 보세요.


예시 1. handset-class-device 프로필로 생성된 오디오


예시 2. telephony-class-application 프로필로 생성된 오디오

참고: 각 오디오 프로필은 오디오 효과 범위를 조정하여 특정 기기에 맞게 최적화되었습니다. 그러나 프로필을 조정하는 데 사용되는 기기의 제조업체 및 모델이 사용자의 재생 기기와 정확히 일치하지 않을 수 있습니다. 애플리케이션에 가장 적합한 사운드 출력을 찾으려면 여러 프로필을 사용하여 실험해야 할 수도 있습니다.

사용 가능한 오디오 프로필

다음 표에는 Text-to-Speech API에서 사용할 수 있는 기기 프로필의 ID와 예시가 나와 있습니다.

오디오 프로필 ID 최적화된 기기
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 홈 엔터테인먼트 시스템 또는 스마트 TV(예: Google Home Max, LG TV)
large-automotive-class-device 차량용 스피커
telephony-class-application 대화형 음성 응답(IVR) 시스템

사용할 오디오 프로필 지정

사용할 오디오 프로필을 지정하려면 음성 합성 요청에 effectsProfileId 필드를 설정합니다.

프로토콜

오디오 파일을 생성하려면 POST 요청을 만들고 적절한 요청 본문을 지정하세요. 다음은 curl을 사용한 POST 요청의 예시입니다. 이 예시에서는 Google Cloud CLI를 사용하여 요청에 대한 액세스 토큰을 검색합니다. gcloud CLI 설치에 대한 안내는 Text-to-Speech에 인증을 참조하세요.

다음 예시에서는 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

요청이 성공하면 Text-to-Speech API는 합성된 오디오를 JSON 출력에 포함된 base64 인코딩 데이터로 반환합니다. audio-profiles.txt 파일의 JSON 출력은 다음과 같습니다.

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

Text-to-Speech용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Text-to-Speech 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Text-to-Speech Go API 참고 문서를 확인하세요.

Text-to-Speech에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import (
	"fmt"
	"io"
	"io/ioutil"

	"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 = ioutil.WriteFile(outputFile, resp.AudioContent, 0644); 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 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

Text-to-Speech용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Text-to-Speech 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Text-to-Speech Node.js API 참고 문서를 확인하세요.

Text-to-Speech에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

Text-to-Speech용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Text-to-Speech 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Text-to-Speech Python API 참고 문서를 확인하세요.

Text-to-Speech에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def synthesize_text_with_audio_profile(text, output, effects_profile_id):
    """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")

    # 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# 설정 안내를 따른 다음 .NET용 Text-to-Speech 참고 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Text-to-Speech 참고 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Text-to-Speech 참고 문서를 참조하세요.