diff --git a/src/main/kotlin/com/sangdol/text_to_speech/SingleTextConverter.kt b/src/main/kotlin/com/sangdol/text_to_speech/SingleTextConverter.kt new file mode 100644 index 0000000..66cb1ba --- /dev/null +++ b/src/main/kotlin/com/sangdol/text_to_speech/SingleTextConverter.kt @@ -0,0 +1,44 @@ +package com.sangdol.text_to_speech + +import com.google.cloud.texttospeech.v1.* +import com.google.protobuf.ByteString +import org.springframework.stereotype.Component +import java.io.File +import java.io.FileOutputStream + +@Component +class SingleTextConverter( + private val ttsClient: TextToSpeechClient +) { + fun convert( + request: ConvertSingleTextRequest, + filePath: String, + language: TtsLanguageCode = TtsLanguageCode.ENGLISH_US, + encodingType: AudioEncoding = AudioEncoding.MP3 + ) { + val synthesisInput = SynthesisInput.newBuilder() + .setText(request.text) + .build() + + val voiceOptions = VoiceSelectionParams.newBuilder() + .setLanguageCode(language.code) + .setName(request.type.identifier) + .build() + + val audioConfig = AudioConfig.newBuilder() + .setAudioEncoding(encodingType) + .setSpeakingRate(request.speakingRate) + .build() + + val synthesizeResponse: SynthesizeSpeechResponse = ttsClient.synthesizeSpeech(synthesisInput, voiceOptions, audioConfig) + val content: ByteString = synthesizeResponse.audioContent + + val file = File(filePath).also { + it.parentFile + .takeIf { dir -> !dir.exists() } + ?.mkdirs() + } + + FileOutputStream(file).use { it.write(content.toByteArray()) } + } +}