如何在javascript中修复语音合成语音

And*_*ard 2 javascript text-to-speech speech-synthesis

每当我运行此代码时,我都会得到一个女性响应,然后第二次我得到一个男性声音,如果我尝试再次运行它,它将无法响应。

这是代码/

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);
Run Code Online (Sandbox Code Playgroud)

小智 5

您的问题似乎不是异步处理Web Speech 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);
});
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)