0

Here i am using js text to speech with SpeechSynthesis and its working fine with limited amount of words/sentences, but the time i add all my blog paragraph which is more then 2-3k words its not working, its converting till some part and automatically being stop. So how can i add unlimited no of words or total page content converted to speech.

NOTE: I tried js speak() also, which worked fine but i want a pause/stop option so i used this. So if there any other working way then please suggest.

const msg = new SpeechSynthesisUtterance();
let voices = [];
const voicesDropdown = document.querySelector('[name="voice"]');
const options = document.querySelectorAll('[type="range"],[name="text"]');
const speakButton = document.querySelector('#speak');
const stopButton = document.querySelector('#stop');

msg.text = document.querySelector('[name="text"]').value;

function populateVoices() {
  voices = this.getVoices();
  voicesDropdown.innerHTML = voices.map(voice => `<option value="${voice.name}">${voice.name}(${voice.lang})</option>`).join('');
}

function setVoice() {
  msg.voice = voices.find(voice => voice.name === this.value);
  toggle();
}

function toggle(startOver = true) { //true is for it will not stop if language changes
  speechSynthesis.cancel();
  if (startOver) {
    speechSynthesis.speak(msg);
  }
}

function setOption() {
  //                console.log(this.name, this.value);
  msg[this.name] = this.value;
  toggle();
}

speechSynthesis.addEventListener('voiceschanged', populateVoices);
voicesDropdown.addEventListener('change', setVoice);
options.forEach(option => option.addEventListener('change', setOption));
speakButton.addEventListener('click', toggle);
<div class="voiceinator">
  <select name="voice" id="voices">
    <option value="">Select a voice</option>
  </select>
  <label for="rate">Rate:</label>
  <input type="range" name="rate" min="0" max="3" value="1" step="0.1">

  <label for="pitch">Pitch:</label>
  <input type="range" name="pitch" min="0" max="2" value="1" step="0.1">

  <textarea name="text"></textarea>
  <button id="stop">Stop!</button>
  <button id="speak">Speak</button>

</div>
Karan
  • 12,059
  • 3
  • 24
  • 40

1 Answers1

3

It's a known bug. The workaround is to issue a resume every 14 seconds.

You can add this immediately after the line speechSynthesis.speak(msg):

let r = setInterval(() => {
  console.log(speechSynthesis.speaking);
  if (!speechSynthesis.speaking) {
    clearInterval(r);
  } else {
    speechSynthesis.resume();
  }
}, 14000);
Frazer
  • 1,049
  • 1
  • 10
  • 16
  • @Rk.Sahoo Thanks for accepting. If you haven't already please upvote the question I've linked to under 'workaround', cheers. – Frazer May 18 '20 at 11:22