Google TTS API 적용기

2024. 3. 6. 17:22Project/2023-02 세종창의학기제

Diff-SVC 프로젝트 내에서 사용자가 텍스트를 통해 입력이 주어지면, 먼저 TTS를 통해 해당 텍스트를 음성으로 변화시키는 작업이 필요하였다. 때문에 외부 API를 사용하기로 회의를 통해 결정하였고, 여러 회사의 API를 고민하던 중 Google Cloud의 Text-To-Speech를 채택하여 사용하기로 하였다.

 

Text-to-Speech는 Google의 인공지능(AI) 기술을 기반으로 한 API로서, API 호출에서 스크립트 데이터를 Text-to-Speech로 전송한 후 자연스럽게 합성된 인간 음성을 재생 가능한 오디오로 변환한다.

Google Cloud에서는 여러 언어 (Java, Node.js ,PHP, Python, Go)로 예시 코드가 제공되어 이를 참조하여 수월하게 개발할 수 있었다. SpringBoot 프레임워크를 사용하기 때문에 Java 예시 코드를 참조하였다.

 

https://cloud.google.com/text-to-speech/docs/samples?hl=ko

 

모든 Text-to-Speech 코드 샘플  |  Cloud Text-to-Speech API  |  Google Cloud

컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. [{ "type": "thumb-down", "id": "hardToUnderstand", "label":"Hard to understand" },{ "type": "thumb-down", "id": "incorrectInformationOrSampleCod

cloud.google.com


API 사용 신청 방법

Text-to-Speech를 사용하려면 먼저 Google Cloud Platform Console에서 API를 사용 설정해야 한다. 

  • 프로젝트에서 Text-to-Speech를 사용 설정.
  • Text-to-Speech에 결제가 사용 설정되었는지 확인.
  • 개발 환경에 인증을 설정.

여기서 주의해야 할 점은 가격에 대한 부분이다.Text-to-Speech 가격은 서비스로 전송되어 오디오로 합성되는 문자 수(영문 기준)를 기준으로 매월 책정된다. Text-to-Speech를 사용하려면 결제를 사용 설정해야 하며 사용량이 월별 무료 문자 수를 초과하면 자동으로 청구된다. 요약한 가격표는 다음과 같다.

Google TTS API 가격표

https://cloud.google.com/text-to-speech/pricing?hl=ko

 

가격 책정  |  Cloud Text-to-Speech  |  Google Cloud

Text-to-Speech 가격 책정 검토

cloud.google.com

 

 

Diff-SVC 프로젝트를 생성 후 활용 신청을 진행하였다. 이후 API 호출에 필요한 인증 정보들을 포함한 json 파일을 받아 저장하였다.

 

 

SpringBoot 개발

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class TTSController {
    private final TTSService ttsService;
    @GetMapping("/convert-to-speech")
    public ResponseEntity<byte[]> convertTextToSpeech(@RequestParam String text) throws Exception {
        byte[] audio = ttsService.convertTextToSpeech(text);
        return ResponseEntity.ok()
                .header("Content-Type", "audio/mpeg")
                .body(audio);
    }

}

 

@GetMapping("/convert-to-speech"): TTS API의 경로로서 HTTP GET 요청을 /api/convert-to-speech 경로와 매핑하며, 이 경로로 들어오는 요청을 이 메소드가 처리하도록 한다.

@RequestParam String text: HTTP 요청에서 사용자가 요청으로 입력한 text라는 이름의 쿼리 파라미터 값을 String 타입으로 받는다.

메소드 내에서는 ttsService.convertTextToSpeech(text)를 호출하여 텍스트를 음성으로 변환하고, 그 결과를 바이트 배열로 받는다.

ResponseEntity.ok()를 통해 HTTP 200 상태 코드와 함께 응답을 생성한다. 헤더에는 "Content-Type"을 "audio/mpeg"로 설정하여 반환되는 컨텐츠가 MP3 오디오로 명시한다.

 

 

@Service
@Slf4j
public class TTSService {
    @Value("${azure.blob.file-name}")
    private String jsonFileName;
    private TextToSpeechClient initializeTtsClient() throws Exception {
        Path path = Paths.get(jsonFileName);
        log.info("path :" + path.toAbsolutePath());
        System.setProperty("GOOGLE_APPLICATION_CREDENTIALS", path.toAbsolutePath().toString());

        String credentialsPath = System.getProperty("GOOGLE_APPLICATION_CREDENTIALS");
        log.info("Set GOOGLE_APPLICATION_CREDENTIALS: " + credentialsPath);

        if (credentialsPath == null || credentialsPath.isEmpty()) {
            throw new Exception("Failed to set GOOGLE_APPLICATION_CREDENTIALS");
        }

        return TextToSpeechClient.create();
    }

    /**
     * https://cloud.google.com/text-to-speech/docs/create-audio?hl=ko
     */

    public byte[] convertTextToSpeech(String text) throws Exception {
        try (TextToSpeechClient textToSpeechClient = initializeTtsClient()) {
            SynthesisInput input = SynthesisInput.newBuilder().setText(text).build();
            VoiceSelectionParams voice = VoiceSelectionParams.newBuilder()
                    .setLanguageCode("ko-KR")
                    .setSsmlGender(SsmlVoiceGender.FEMALE)
                    .build();
            AudioConfig audioConfig = AudioConfig.newBuilder().setAudioEncoding(AudioEncoding.MP3).build();

            SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);
            return response.getAudioContent().toByteArray();
        }
    }
}

 

initializeTtsClient() 메서드

- Path path = Paths.get(jsonFileName) : jsonFileName에서 제공한 파일 경로를 사용하여 Path 객체를 생성.

- 시스템 속성 GOOGLE_APPLICATION_CREDENTIALS을 인증 파일 경로로 설정. 이는 Google API 클라이언트가 인증 정보를 찾는 데 사용함으로서 필수적인 작업이다.

- TextToSpeechClient.create()를 호출하여 Google Text-to-Speech API를 사용할 클라이언트 인스턴스를 생성한다.

 

convertTextToSpeech() 메서드

- 해당 메서드는 Google의 Text-to-Speech API를 사용하여 입력된 텍스트를 음성 데이터로 변환.

- SynthesisInput 객체를 사용하여 변환할 텍스트를 설정.

- VoiceSelectionParams 객체를 사용하여 음성의 언어 코드와 성별을 설정. 여기서는 한국어와 여성 목소리를 선택.

- AudioConfig 객체를 통해 오디오 출력 형식을 MP3로 설정.

- textToSpeechClient.synthesizeSpeech(input, voice, audioConfig) 메소드를 호출하여 텍스트를 음성으로 변환하고, 그 결과를 SynthesizeSpeechResponse 객체로 받는다.

-> 최종적으로, 음성 데이터(response.getAudioContent())를 바이트 배열로 변환하여 반환.