Lavanda
Lavanda

Reputation: 11

Speech Synthesis - chrome, using different voice breaks text

I have a long piece of text to be read and I wanted to use a different voice, voice[4], but after 10-15 seconds the speech stops.

I have a play/pause button which resumes the text where it last ended, and that works fine.

Also if I'm using the default voice it reads the whole text, but I'm hoping to be able to change the voice and have it still work properly.

If anyone can help me I would appreciate it. Note that I am using Chrome.

var isSpeaking = false;
var paused = false;
var speech;

document.getElementById('readButton').addEventListener('click', function() {
  var icon = document.getElementById('playButton');
  if (icon.classList.contains('fa-circle-play') && !paused) {
    icon.classList.remove("fa-circle-play");
    icon.classList.add("fa-circle-pause");
    startSpeaking();
  } else if (icon.classList.contains('fa-circle-play') && paused) {
    icon.classList.remove("fa-circle-play");
    icon.classList.add("fa-circle-pause");
    resumeSpeaking();
  } else if (icon.classList.contains('fa-circle-pause')) {
    icon.classList.remove("fa-circle-pause");
    icon.classList.add("fa-circle-play");
    stopSpeaking();
  }
});

function startSpeaking() {

  if (!isSpeaking) {
    var mainContent = document.getElementById('articleBody');
    var textToRead = mainContent.innerText;

    if ('speechSynthesis' in window) {
      speech = new SpeechSynthesisUtterance(textToRead);
      speech.lang = 'en-EN';
      speech.volume = 1;
      speech.rate = 1;
      speech.pitch = 1.1;

      speechSynthesis.onvoiceschanged = function() {

        var voices = window.speechSynthesis.getVoices();
        speech.voice = voices[4];
        window.speechSynthesis.speak(speech);

        isSpeaking = true;
      };

    } else {
      alert('Browser-ul tău nu suportă funcția de vorbire text!');
    }
  }
}

function stopSpeaking() {
  if (isSpeaking) {
    window.speechSynthesis.pause();
    isSpeaking = false;
    paused = true;
  }
}

function resumeSpeaking() {
  if (!isSpeaking && paused) {
    window.speechSynthesis.resume();
    isSpeaking = true;
    paused = false;
  }
}

Upvotes: 1

Views: 69

Answers (0)

Related Questions