In a webpage, I want a female voice to speak my texts. I tried to do this by following code. But still now male voice is talking. How can I arrange a female voice to talk my texts? Can anybody share me a correct code that works in Google Chrome.
var voices = speechSynthesis.getVoices();
var msg = new SpeechSynthesisUtterance("Hello World!");
msg.default=false;
msg.localservice=true;
msg.lang = "en-GB";
msg.voice = voices[3].name;
speechSynthesis.speak(msg);
While working on my React.js project, I figured out that you have to reference them by the whole object rather than just the name. Here is how I used it in my code and it worked... Only thing is that there is a 4th element on the array of voices named Hubert and it doesn't seem to work so you could opt out by removing the last element of that array as I did by slicing the mapped array "(0,-1)".
const [selectedVoice, setSelectedVoice] = useState();
const handleVoiceChange = (e) => {
const selectedVoiceIndex = e.target.value;
const voices = window.speechSynthesis.getVoices().slice(0,-1);
const voice = voices[selectedVoiceIndex]
console.log("current voice:", voice.name);
if (voice) {
setSelectedVoice(voice);
} else {
console.warn("Selected voice not found.");
}
};
<select onChange={handleVoiceChange}>
{window.speechSynthesis.getVoices().slice(0,-1).map((voice, index) => (
<option key={index} value={index}>
{voice.name}
</option>
))}
</select>