Текст в речь выделенного текста - PullRequest
0 голосов
/ 05 февраля 2019

для вопросника, который частично предназначен для людей, которые не умеют читать, мне нужно приложение для преобразования текста в речь.Из соображений удобства использования текст следует читать, когда он выделен цветом («помечен»).Исследуя различные способы, как это сделать, я нашел следующий инструмент, который должен это делать.По некоторым причинам это не будет работать.Я хочу использовать его в программном обеспечении для опросов SoSci, так что это может быть проблемой (у кого-нибудь есть опыт там?).

Буду признателен за любой намек, чего мне не хватает, но также приветствуются и другие подходы к решению проблемы!

С наилучшими пожеланиями

<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 ]

0 голосов
/ 05 февраля 2019

Объяснил

Хорошо, я упомянул, что вы узнаете, как использовать SpeechSynthesis, вы сказали, что чувствуете, что недостаточно сильны как программист для реализации приложения.который использует эту функцию.Между документацией, которую вы можете найти в MDN, и демонстрацией, которую я собираюсь вам показать, вы сможете реализовать такую ​​функцию без особых проблем.

Я предлагаю вам избегать использования библиотек с очень простыми функциями, которые действуют как обертка вокруг нативной технологии, она мешает вам изучить основную технологию.Я имею в виду, во что бы то ни стало, используйте их в качестве отправной точки, но я полагаю, что вы изучили нативный подход позднее, это поможет вам продвинуться как разработчик, по крайней мере, это мое мнение.

Демонстрация

В этой демонстрации я в значительной степени скопировал и вставил код, который можно найти в MDN.

Единственным отличием моего кода от кода, который можно найти в MDN, является тот факт, что я использую "use strict;" и немедленно вызываемую вызываемую функцию.В этом случае я бы посоветовал вам прочитать больше о строгом режиме и 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

Я надеюсь, что это так или иначе помогло вам, всего наилучшего!:)

0 голосов
/ 05 февраля 2019

Причина, по которой он не будет работать постоянно, в том, что вы используете библиотеку Text-2-Speech.Кажется, иногда не удается загрузить. Проверьте ваш код здесь .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...