Technologies:
Tolerim
a month ago
How can I use JavaScript to choose different Google voices in the Google Text-to-Speech API?
As a JavaScript developer building a chatbot with TTS support, I am facing an issue where the gender selection radio buttons are not functioning as expected. Despite selecting the male voice option, the TTS API always returns a female voice. I have been trying to debug this issue for some time now, but I am unable to find a solution. Here's the relevant code:
googleTTS.api
import { TextToSpeechClient } from "@google-cloud/text-to-speech";
import { config as loadEnvConfig } from "dotenv";
loadEnvConfig();
const client = new TextToSpeechClient({
keyFilename: process.env.GOOGLEAPPLICATIONCREDENTIALS,
});
export default async function (req, res) {
const { text, voice } = req.body;
console.log(`Received voice: ${voice}`);
const voiceName = voice === "male" ? "en-US-Wavenet-D" : "en-AU-Wavenet-C";
const languageCode = voice === "male" ? "en-US" : "en-AU";
const ssmlGender = voice === "male" ? "MALE" : "FEMALE";
const voiceConfig = {
name: voiceName,
languageCode: voiceName.slice(0, 5),
ssmlGender: voice === "male" ? "MALE" : "FEMALE",
};
console.log(`Received voiceConfig: ${JSON.stringify(voiceConfig)}`);
const audioConfig = {
audioEncoding: "MP3",
};
const request = {
input: { text },
voice: voiceConfig,
audioConfig,
};
try {
const [response] = await client.synthesizeSpeech(request);
const audioContent = response.audioContent;
res.setHeader("Content-Type", "audio/mpeg");
res.send(Buffer.from(audioContent, "binary"));
} catch (error) {
console.error(`Error with Google TTS API request: ${error.message}`);
res.status(500).json({
error: {
message: "An error occurred during your request",
},
});
}
}
index.jsx
setPromptInput("");
const ttsEndpoint = ttsProvider === "ElevenLabs" ? "/api/elevenLabs" : "/api/googleTTS";
const voiceParam = ttsProvider === "GoogleTTS" ? (voice === "female" ? "en-AU-Wavenet-C" : "en-US-
Wavenet-D") : (voice === "female" ? "female" : "male");
console.log(`Selected voice: ${voice}`);
console.log(`Sending voice to TTS API: ${voiceParam}`);
I'm hoping someone with expertise in JavaScript will be able to assist me with this specific issue.Answers(1)
Tolerim
a month ago
Verified Answer
Based on the code provided, it looks like the issue might be with the voiceName variable. You are setting it to "en-US-Wavenet-D" if the voice parameter is "male" and "en-AU-Wavenet-C" if it's "female". However, in the voiceConfig object, you are using voiceName.slice(0, 5) as the languageCode, which means that it will always be "en-US" or "en-AU" regardless of the voice parameter.
To fix this, you should set languageCode based on the languageCode variable instead of voiceName:
name: voiceName,
languageCode: languageCode,
ssmlGender: ssmlGender,
};
This should ensure that the correct voice is used based on the selected gender.