当函数运行超过1次时,为什么我的Speech Synthesis API语音会改变?

Phi*_*ung 8 javascript text-to-speech speech-synthesis google-text-to-speech

我一直在Chrome(33及以上版本)中使用新的语音合成API来制作基于Web的通信辅助工具.我希望用户能够改变男性和女性之间的声音,API允许我这样做.但是,当首次加载页面并且第一次运行该功能时(来自onclick事件),它将使用默认的女性语音.然后在任何时候运行它,它使用我试图使用的男性声音.我怎样才能让男声第一次出现?

这是调用javascript的按钮:

<button type="button" name="speakMe"id="speakMe" onclick="speakPhrase($('phraseBar').getValue());" ><img src="images/speakMe.png" /></button>
Run Code Online (Sandbox Code Playgroud)

这里是speakPhrase函数被调用:

function speakPhrase(phrase) {
    if(phrase =="")
    {
        alert("Please enter a phrase before asking me to speak for you. Thank you!");
    }
    else
    {
        var speech = new SpeechSynthesisUtterance(phrase);
        var voices = window.speechSynthesis.getVoices();
        speech.voice = voices.filter(function(voice) { return voice.name == 'Google UK English Male'; })[0];
        window.speechSynthesis.speak(speech);

    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

ago*_*dev 7

似乎第一次调用时声音数组是空的.根据我的阅读,它与异步调用加载声音有关.所以,它第一次被调用时总是空的.对我来说这就是魔术:

var speech_voices;
if ('speechSynthesis' in window) {
  speech_voices = window.speechSynthesis.getVoices();
  window.speechSynthesis.onvoiceschanged = function() {
    speech_voices = window.speechSynthesis.getVoices();
  };
}
Run Code Online (Sandbox Code Playgroud)

从言语功能之外的某个地方打电话.


Phi*_*ung 0

幸运的是,我在设置语音之前将默认属性设置为 false 成功解决了这个问题

function speakPhrase(phrase) {
    if(phrase =="")
    {
        alert("Please enter a phrase before asking me to speak for you. Thank you!");
    }
    else
    {
        var speech = new SpeechSynthesisUtterance(phrase);
        var voices = window.speechSynthesis.getVoices();
        speech.default = false;
        speech.voice = voices.filter(function(voice) { return voice.name == 'Google UK English Male'; })[0];
        speech.lang = 'en-GB'; //Also added as for some reason android devices used for testing loaded spanish language 
        window.speechSynthesis.speak(speech);
    }
}
Run Code Online (Sandbox Code Playgroud)