Изменение голоса SpeechSynthesis не работает - PullRequest
0 голосов
/ 03 апреля 2020

Я перепробовал все варианты, которые я могу найти в stackoverflow, но я все еще не могу заставить голос измениться в SpeechSynthesis

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

К сожалению, этот код не меняет голос. Также перед сменой голоса. msg.voice имеет значение null, хотя оно использовалось для перечисления всех доступных голосов.

Может кто-нибудь сказать мне, что не так с кодом? (console.log (msg.voice); перед установкой возвращает ноль)

<!doctype html>
<html>
<head>
<SCRIPT>
var msg = new SpeechSynthesisUtterance();
voices = window.speechSynthesis.getVoices();
var numberOfVoices=0;


function Main(){
voiceSelect=document.getElementById("voiceSelect");
setTimeout(getVoicesFunction,2000);
}

function getVoicesFunction(){
msg = new SpeechSynthesisUtterance("hello");
numberOfVoices=0;   
speechSynthesis.getVoices().forEach(function(voice) {
var option = document.createElement('option');
        option.text = option.value = voice.voiceURI;
        voiceSelect.add(option, 0);
        numberOfVoices=numberOfVoices+1;
});
    voiceSelect.onchange = voiceChange;
}

function voiceChange(){
    textToSpeech("this is the old voice");
    var selectedOption = this[this.selectedIndex];
    selectedVoice = selectedOption.text;
    msg = new SpeechSynthesisUtterance();
    voices = window.speechSynthesis.getVoices();
    msg = new SpeechSynthesisUtterance();
    console.log("before change msg.voice");
    console.log(msg.voice);
    for(i = 0; i < numberOfVoices ; i++) {
    if(voices[i].voiceURI === selectedVoice) {
    var temp="changing the voice number to "+i;
    setTimeout(textToSpeech,2000,temp);
    msg.voice = voices[i];
    console.log(msg.voice);
    var tempVoiceNumber=i;
    };
    }
    setTimeout(textToSpeech,4000,"this is the new voice");
}

function textToSpeech(tspeech){
    msg = new SpeechSynthesisUtterance();
    msg.text = tspeech;
    speechSynthesis.speak(msg);
    console.log("speech "+tspeech);
}       
</SCRIPT>
</head>
<body onload= "Main()" id= "mainb">
<div id="container">
<select name="Combobox1" size="1" id="voiceSelect">
</select>
</div>
</body>
</html>

1 Ответ

0 голосов
/ 04 апреля 2020

IanR, я скопировал код, и он работает для меня. Я отключил контроль высоты тона и скорости и сделал html более простым, но в основном он такой же.

Если он не работает для вас, вы получаете какие-либо ошибки консоли?

var synth = window.speechSynthesis;

var inputForm = document.querySelector('form');
var inputTxt = document.querySelector('.txt');
var voiceSelect = document.querySelector('select');

/*var pitch = document.querySelector('#pitch');
var pitchValue = document.querySelector('.pitch-value');
var rate = document.querySelector('#rate');
var rateValue = document.querySelector('.rate-value');*/



var voices = [];

function populateVoiceList() {
  voices = synth.getVoices();

  for (i = 0; i < voices.length; i++) {
    var option = document.createElement('option');
    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';

    if (voices[i].default) {
      option.textContent += ' -- DEFAULT';
    }

    option.setAttribute('data-lang', voices[i].lang);
    option.setAttribute('data-name', voices[i].name);
    voiceSelect.appendChild(option);
  }
}

populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
  speechSynthesis.onvoiceschanged = populateVoiceList;
}

inputForm.onsubmit = function(event) {
  event.preventDefault();

  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
  for (i = 0; i < voices.length; i++) {
    if (voices[i].name === selectedOption) {
      utterThis.voice = voices[i];
    }
  }
  //utterThis.pitch = pitch.value;
  //utterThis.rate = rate.value;
  synth.speak(utterThis);

  inputTxt.blur();
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>61016951</title>
  <script src="61016951.js" defer></script>
</head>

<body>
  <div id="div">
    <form>
      <input type="text" class="txt">
      <select></select>
      <button type="submit">Play</button>
    </form>
  </div>
</body>

</html>
...