Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change voice in Speech Synthesis?

I am trying out a simple example with Speechsynthesis.

<script>

voices = window.speechSynthesis.getVoices()
var utterance = new SpeechSynthesisUtterance("Hello World");
utterance.voice = voices[4];
utterance.lang = voices[4].lang;
window.speechSynthesis.speak(utterance);

</script>

But this gives an error that voices is undefined. I found that getVoices() is loaded async. I saw this answer and updated my code as shown below to use callback.

<script>
window.speechSynthesis.onvoiceschanged = function() {
voices = window.speechSynthesis.getVoices()
var utterance = new SpeechSynthesisUtterance("Hello World");
utterance.voice = voices[4];
utterance.lang = voices[4].lang;
window.speechSynthesis.speak(utterance);
};
</script>

But due to some strange reason, the text is spoken three times instead of one. How can I fix this code?

like image 459
codingsplash Avatar asked Mar 09 '17 11:03

codingsplash


People also ask

How do I change my safari voice?

Choose a voice On your Mac, choose Apple menu > System Preferences, click Accessibility , then click Spoken Content. Click the System Voice pop-up menu, then choose a voice. To adjust how fast the voice speaks, drag the Speaking Rate slider. Click Play to test the voice and speaking rate.

How do I change the default voice in Windows 10?

To change voice settings: Open the Start menu on your Windows device and select Settings > Time & Language. Select Speech.


1 Answers

I can't replicate your issue, but try adding an event listener so that your function runs after the voices are loaded.

let voices, utterance;

function speakVoice() {
voices = this.getVoices();
utterance = new SpeechSynthesisUtterance("Hello World");
utterance.voice = voices[1];
speechSynthesis.speak(utterance);
};

speechSynthesis.addEventListener('voiceschanged', speakVoice);
like image 75
Andrew Avatar answered Sep 25 '22 16:09

Andrew