texttospeech.go 1.56 KiB
Newer Older
package googleapi

import (
	"net/http"

	"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/loggermdl"
	texttospeech "google.golang.org/api/texttospeech/v1beta1"
)

//TextConfig Google Text-to-Speech config
type TextConfig struct {
	Text          string
	LanguageCode  string
	AudioEncoding string
}

//TextToSpeech get the text to speech
func TextToSpeech(client *http.Client, c TextConfig) (string, error) {
	loggermdl.LogInfo("IN TextToSpeech")
	texttospeechService, err := texttospeech.New(client)
	if c.AudioEncoding == "" {
		c.AudioEncoding = "MP3"
	}
	if c.LanguageCode == "" {
		c.LanguageCode = "en-IN"
	}
	if err != nil {
		loggermdl.LogError("texttospeechService Error: ", err)
		loggermdl.LogInfo("OUT TextToSpeech")
		return "", err
	}
	ttsConfig := texttospeech.AudioConfig{
		AudioEncoding: c.AudioEncoding,
	}
	inputText := texttospeech.SynthesisInput{
		Text: c.Text,
	}
	voiceParams := texttospeech.VoiceSelectionParams{
		LanguageCode: c.LanguageCode,
	}
	ttsSpeechReq := texttospeech.SynthesizeSpeechRequest{
		AudioConfig: &ttsConfig,
		Input:       &inputText,
		Voice:       &voiceParams,
	}
	ttsSpeechCall := texttospeechService.Text.Synthesize(&ttsSpeechReq)
	syncResponse, err := ttsSpeechCall.Do()
	if err != nil {
		loggermdl.LogError("ttsSpeechCall Error", err)
		loggermdl.LogInfo("OUT TextToSpeech")
		return "", err
	}
	resp, err := syncResponse.MarshalJSON()
	if err != nil {
		loggermdl.LogError("syncResponse Error", err)
		loggermdl.LogInfo("OUT TextToSpeech")
		return "", err
	}
	loggermdl.LogInfo("OUT TextToSpeech")
	return string(resp), nil
}