如何在javascript

时间:2016-04-02 18:40:53

标签: 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);

2 个答案:

答案 0 :(得分:3)

您的问题似乎不是异步处理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);
});

这是你每次都能得到你想要的声音的一种方式(通过评论注意我的变化):

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)

答案 1 :(得分:0)

好的,我知道问题是什么。如此链接中所述:https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis/onvoiceschanged语音列表仅在speechSynthesis.onvoiceschanged事件被触发后才可用。

这是帮助的小提琴:https://jsfiddle.net/mx2edhvw/1/

需要注意的一点是speak是对系统的说法。在再次发言之前,您需要先cancel,否则您会继续添加更多内容。