如何修复 javascript 中的语音合成发音

how to fix Speech Synthesis Utterance in javascript

每当我 运行 这个代码我得到一个女性的回应,然后我第二次得到一个男性的声音,如果我再次尝试 运行 它没有回应。

这是代码/

var aiload = document.getElementById('ai').innerHTML
var msg = new SpeechSynthesisUtterance(aiload);
var voices = window.speechSynthesis.getVoices();

voices.forEach(function (voice, i) {
    var voiceName = 'Google UK English Female';
    var selected = '';

    if(voiceName == 'native') {
        selected = 'selected';
    }
    var option = "<option value='" + voiceName + "' " + selected + " >" + voiceName + "</option>";
    voiceSelect.append(option);
    console.log(voiceName);
});

msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 0; //0 to 2
msg.text = aiload;
msg.lang = 'en-US';

msg.onend = function(e) {
    console.log('Finished in ' + event.elapsedTime + ' seconds.');
};


speechSynthesis.speak(msg);

好的,我知道问题出在哪里了。如此 link 中所述:https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis/onvoiceschanged 语音列表仅在 speechSynthesis.onvoiceschanged 事件触发后可用。

这里有一个 fiddle 帮助:https://jsfiddle.net/mx2edhvw/1/

需要注意的一件重要事情是 speak 向系统添加了 话语。你需要做一个 cancel 再说之前,否则你会继续添加更多。

您的问题似乎不是异步处理 Web 语音 API。

现在不需要以下代码片段,但我想指出,您似乎从未在任何地方更改 voiceName 变量,因此 if 语句看起来没有必要:

voices.forEach(function (voice, i) {
    var voiceName = 'Google UK English Female';
    var selected = '';

    if(voiceName == 'native') {
        selected = 'selected';
    }
    var option = "<option value='" + voiceName + "' " + selected + " >" + voiceName + "</option>";
    voiceSelect.append(option);
    console.log(voiceName);
});

这是您每次都能获得想要的声音的一种方法(请注意我的评论更改):

var aiload = document.getElementById('ai').innerHTML;

// Use setInterval to keep checking if the voices array has been filled prior to creating the speech utterance
var voiceGetter = setInterval(function() {
  var voices = window.speechSynthesis.getVoices();
  if (voices.length !== 0) {
    var msg = new SpeechSynthesisUtterance(aiload);
    // Pick any voice from within the array; you can console.log(voices) to see options
    msg.voice = voices[5];
    msg.volume = 1;
    msg.rate = 1;
    msg.pitch = 0;
    // msg.text = aiload; <== This is redundant because of how msg is defined
    msg.lang = 'en-US';
    msg.onend = function(e) {
        console.log('Finished in ' + event.elapsedTime + ' seconds.');
    };
    speechSynthesis.speak(msg);
    clearInterval(voiceGetter);
  }
}, 200)