Custom code text to speech with pause, stop, replay | XM Community
Skip to main content

Hello,
I am trying to figure out how to have my landing page read aloud text-to-speech (one block of text) but want respondents to be able to pause and replay as needed. It would only be for this question. I am not familiar with JavaScript/HTML and have searched through previous posts to come up with a messy script that will read the text when I click the microphone button, and will display speak/pause/stop buttons (but those buttons do not work). Any ideas for the code to let me pause/stop/replay?
Thanks!
Katie

HTML:



Hello and thank you for considering agreeing to participate in this study – we know your time is limited and greatly appreciate your willingness to share your professional expertise with us.  



JavaScript:
Qualtrics.SurveyEngine.addOnReady(function()
{
const questionTextContainer = this.getQuestionTextContainer();
const questionText = questionTextContainer.innerText;

var txtInput = document.querySelector('#txtInput');
var btnSpeak = document.querySelector('#btnSpeak');
var synth = window.speechSynthesis;
var voices = =];

function PopulateVoices(){
 voices = synth.getVoices();
 voices.forEach((item, index) => console.log(item.name, index));

}

btnSpeak.addEventListener('click', ()=> {
 var toSpeak = new SpeechSynthesisUtterance(txtInput.textContent);
toSpeak.volume = 1;
toSpeak.pitch = 1;
toSpeak.rate = 1;
 toSpeak.voice = voicesv0]; 
 synth.speak(toSpeak);

});

function pause()
{
  speechSynthesis.pause();
}

function stop()
{
  speechSynthesis.cancel();
}

speakBtn.addEventListener('click', textToSpeech);
pauseBtn.addEventListener('click', pause);
cancelBtn.addEventListener('click', stop);

window.speechSynthesis.cancel();

});

Hi kef0808,
I'm not familiar with writing text to speech code, but for starters your JavaScript isn't assigning the event listeners properly. You've created elements with the iIDs speakBtn, pauseBtn and cancelBtn in the HTML, but JavaScript doesn't automatically know to look there. You need to define them like you've defined "btnSpeak":
var speakBtn = document.querySelector('#speakBtn');
var pauseBtn = document.querySelector('#pauseBtn');
var cancelBtn = document.querySelector('#cancelBtn');

speakBtn.addEventListener('click', textToSpeech);
pauseBtn.addEventListener('click', pause);
cancelBtn.addEventListener('click', stop);
A cursory look at the SpeechSynthesis docs looks like you've set up the pause and stop functions correctly, but I can't see that you've created a function for textToSpeech. You should be able to repurpose the code you already have bound to btnSpeak.
Good luck!


Leave a Reply