代码之家  ›  专栏  ›  技术社区  ›  Phil Young

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

  •  9
  • Phil Young  · 技术社区  · 10 年前

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

    下面是调用javascript的按钮:

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

    下面是调用的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);
    
        }
    }
    

    有人能帮忙吗?

    4 回复  |  直到 10 年前
        1
  •  10
  •   agoldev    9 年前

    语音阵列似乎在第一次调用时为空。从我读到的内容来看,它与加载语音的异步调用有关。所以,第一次调用时总是空的。对我来说,这有魔力:

    var speech_voices;
    if ('speechSynthesis' in window) {
      speech_voices = window.speechSynthesis.getVoices();
      window.speechSynthesis.onvoiceschanged = function() {
        speech_voices = window.speechSynthesis.getVoices();
      };
    }
    

    从语音功能以外的地方调用。

        2
  •  1
  •   user5958722    7 年前

    我解决了这个问题。

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

    所以我在页面加载或开始或就绪状态下添加了以下代码行,这甚至在我的代码被调用之前:

    voices = window.speechSynthesis.getVoices();
    

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

        3
  •  0
  •   Phil Young    10 年前

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

    更新的答案。这对我很有用。

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