Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当函数运行超过1次时,为什么语音合成API语音会发生变化?_Javascript_Text To Speech_Speech Synthesis_Google Text To Speech - Fatal编程技术网

Javascript 当函数运行超过1次时,为什么语音合成API语音会发生变化?

Javascript 当函数运行超过1次时,为什么语音合成API语音会发生变化?,javascript,text-to-speech,speech-synthesis,google-text-to-speech,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="speakPh

我一直在使用Chrome(33及以上)中的新语音合成API制作基于web的通信辅助工具。我希望用户能够改变男性和女性之间的声音,API允许我这样做。但是,当第一次加载页面并且第一次运行函数时(从onclick事件),它使用默认的女性语音。之后的任何时候,它都会使用我试图使用的男性声音。我怎样才能让男性的声音在第一次播放呢

下面是调用javascript的按钮:

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

有人能帮忙吗?

幸运的是,我在设置语音之前将默认属性设置为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);
    }
}

第一次呼叫时,语音数组似乎为空。据我所知,它与加载语音的异步调用有关。所以,它第一次被调用时总是空的。对我来说,这真的很神奇:

var speech_voices;
if ('speechSynthesis' in window) {
  speech_voices = window.speechSynthesis.getVoices();
  window.speechSynthesis.onvoiceschanged = function() {
    speech_voices = window.speechSynthesis.getVoices();
  };
}
从语音功能以外的地方打电话。

我解决了这个问题

根本原因:当您第一次调用API时,由于某种原因语音无法加载。和第一次默认语音加载

因此,我在页面加载或启动或就绪状态(甚至在我的代码被调用之前)添加了以下代码行:

voices = window.speechSynthesis.getVoices();

这解决了我的问题,希望能帮助他人。

更新答案。这对我来说很有用

$(window).load(function(){ voices = window.speechSynthesis.getVoices(); })

如果在第一次呼叫后使用console.log voices,则很容易看到问题。OnVoiceSchange会在更新真正可用时立即更新。
$(window).load(function(){ voices = window.speechSynthesis.getVoices(); })