Install Config Wiki

All about installing, configuring and troubleshooting

User Tools

Site Tools


wiki:wordpress_script_to_add_responsivevoice_api_custom_html_widget

WordPress Script to Add ResponsiveVoice API Custom HTML Widget

This script can be used to enable your entire WordPress Website to perform text-to-speech by calling the ResponsiveVoice API. It utilizes responsivevoice.js and jquery-2.1.4.min.js.

You can modify one line of a function to set the default voice and language. The voice and language will otherwise default to “UK English Female” if not set.

In WordPress, it is suggested that you should place the script in a new “HTML” Widget, that is preferably located in your footer widget area. Why? The script is actually supposed to be placed near the bottom of an html page just before the closing </body> tag. Placing the hidden html widget in the footer should ensure that every page (that includes the footer) will have this script available for every article posted on your blog and every static page. Whenever any text is selected/highlighted, for example using your mouse (a mouse-drag) on any page or article, will cause the text to be read/spoken aloud using this text to voice functionality. One problem is that if the text is spoken and it remains selected, then it may be repeated when you click a hyperlink to move to another page or article.

Here is the script:

<script src="https://code.responsivevoice.org/responsivevoice.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
 
<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.setDefaultVoice("US English Male"); // this sets the default voice and language
         responsiveVoice.speak(getSelectionText()); //speak the text as returned by getSelectionText
      }, 1);
   });
});
</script>
wiki/wordpress_script_to_add_responsivevoice_api_custom_html_widget.txt · Last modified: 2020/05/28 20:58 by wikiadmin