1

for a questionnaire which is partly for people who can't read, I would need a text to speech application. For reasons of usability, the text should be read when highlighted ("marked"). While researching different ways on how to do this, I found the following tool, which should exactly do that. For some reasons it won't work. I want to use it on the questionnaire software SoSci, so that might be an issue (does anybody have any experience there?).

I would appreciate any hint, what I am missing, but also other approaches on how to solve the problem are more than welcome!

Best wishes

<script>        
function getSelectionText() {
        var text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        // for Internet Explorer 8 and below. For Blogger, you should use &amp;&amp; instead of &&.
        } else if (document.selection && document.selection.type != "Control") { 
            text = document.selection.createRange().text;
        }
        return text;
    }
    $(document).ready(function (){ // when the document has completed loading
       $(document).mouseup(function (e){ // attach the mouseup event for all div and pre tags
          setTimeout(function() { // When clicking on a highlighted area, the value stays highlighted until after the mouseup event, and would therefore stil be captured by getSelection. This micro-timeout solves the issue. 
             responsiveVoice.cancel(); // stop anything currently being spoken
             responsiveVoice.speak(getSelectionText()); //speak the text as returned by getSelectionText
          }, 1);
       });
    });
    </script>
2
  • Have you thought about trying to use SpeechSynthesis in a more native fashion? Feb 5, 2019 at 14:54
  • I have read about it. Unfortunately my knowledge is not good enough to program it. Hence, I need somebody who used is before and is kind enough to share the code.
    – InPanic
    Feb 5, 2019 at 15:01

2 Answers 2

5

Explained

Okay, so I mentioned that you learn how to use SpeechSynthesis, you said that you feel that you're not strong enough as a programmer to implement an application that utilises this feature. Between the documentation that you can find on MDN and this demonstration that I'm about to show you, you should be able to implement such a feature without too much trouble.

I suggest that you try to avoid using libraries that do very simple features, aka act as a wrapper around the native technology, it prevents you from learning the underlying technology. I mean by all means, use them as a starting point, but I suggest that you learnt the native approach at a later date, this will help you progress as a developer, at least that's my opinion.

Demo

With this demo, I've pretty much copied & pasted code that can be found on MDN.

The only differences with my code and the code that can be found on MDN is the fact that I'm using "use strict;" and a immediately invoked invoked function. In which case I'd usggest that you read more about strict mode and IIFE.

// A simple IIFE function. 
(function() {
  "use strict"; // For the sake of practice.

  if (typeof speechSynthesis === 'undefined')
    return;

  // Some config stuffs... 
  var voiceSelect = document.getElementById("voiceSelect");
  var myPhrase = 'Hello World!';
  var voices = [];
  
  // This is essentially similar to jQuery's $.ready.
  var ready = function(callback) { 
    var d = document, s = d.readyState;

    // DOMContentLoaded was fired
    if (s == "complete" || s == "loaded" || s == "interactive") {
      callback();
    } else {
      if (d.addEventListener) {
        d.addEventListener("DOMContentLoaded", callback, false);
      } else {
        d.attachEvent("onDOMContentLoaded", callback);
      }
    }
  };

  // This is a function to display all possible voice options. 
  function populateVoiceList() {
    voices = speechSynthesis.getVoices();

    for (var i = 0; i < voices.length; i++) {
      var option = document.createElement('option');
      option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
      option.textContent += voices[i].default ? ' -- DEFAULT' : '';
      option.setAttribute('data-lang', voices[i].lang);
      option.setAttribute('data-name', voices[i].name);
      document.getElementById("voiceSelect").appendChild(option);
    }
  }

  // This is the handler for when the select tag is changed. 
  function handler() {
    var utterThis = new SpeechSynthesisUtterance(myPhrase);
    var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');

    for (var i = 0; i < voices.length; i++) {
      if (voices[i].name === selectedOption) {
        utterThis.voice = voices[i];
      }
    }

    speechSynthesis.speak(utterThis);
  };

  // This is your code to get the selected text.
  function getSelectionText() {
    var text = "";
    if (window.getSelection) {
      text = window.getSelection().toString();
      // for Internet Explorer 8 and below. For Blogger, you should use &amp;&amp; instead of &&.
    } else if (document.selection && document.selection.type != "Control") {
      text = document.selection.createRange().text;
    }
    return text;
  }

  // This is the on mouse up event, no need for jQuery to do this. 
  document.onmouseup = function(e) {
    setTimeout(function() {
      speechSynthesis.cancel();
      myPhrase = getSelectionText();
      handler();
    }, 1);
  };

  // Some place for the application to start. 
  function start() {
    populateVoiceList();
    if (speechSynthesis.onvoiceschanged !== undefined)
      speechSynthesis.onvoiceschanged = populateVoiceList;

    voiceSelect.onchange = handler;
    setTimeout(handler, 75);
  }

  // Run the start function. 
  ready(start);
})();
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis/getVoices -->
<hr/>
<select id="voiceSelect"></select>
<hr/>
<p>Testing... Testing... One Two Three... Testing</p>
<p>I like big butts and I can not lie, you other brothers can't deny!</p>


PS

I hope that this has helped you in some way or another, all the best! :)

2
  • 1
    Thank you for all the effort! The only thing I still have to figure out is how to play a text due to highlighting it. But thank you again for explaining everything in such detail :)
    – InPanic
    Feb 5, 2019 at 15:54
  • @InPanic I've one a very quick demo of what you could do if you want to implement such a feature! :) Feb 5, 2019 at 15:59
0

The reason it won't work all the time is because of the Text-2-Speech library you're using. It seems to fail to load sometimes. Check your code here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.